Pandas provides a convenient way to read datetime data from CSV or other text files using the parse_dates parameter in the read_csv() function. This parameter allows you to specify which columns should be parsed as datetime objects.
Here's an example:
import pandas as pd# create a dataframe with a date column and a value columndf = pd.DataFrame({ 'date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04'], 'value': [10, 20, 30, 40]})# print the original dataframeprint(df)# read the dataframe with parse_dates parameter to parse the date columndf = pd.read_csv('data.csv', parse_dates=['date'])# print the updated dataframeprint(df) |
In this example, we first create a Pandas dataframe with a date column and a value column. We then print the original dataframe to the console.
Next, we use the read_csv() function to read a CSV file called data.csv. We use the parse_dates parameter to specify that the date column should be parsed as a datetime object. Pandas will automatically parse the dates in the specified column and convert them to datetime objects.
Finally, we print the updated dataframe to the console to see the results.
Note that you can also use the pd.to_datetime() function to convert a column of strings to a datetime object after the dataframe has been loaded. Here's an example:
import pandas as pd# create a dataframe with a date column and a value columndf = pd.DataFrame({ 'date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04'], 'value': [10, 20, 30, 40]})# print the original dataframeprint(df)# convert the date column to a datetime object using pd.to_datetime()df['date'] = pd.to_datetime(df['date'])# print the updated dataframeprint(df) |
In this example, we use the pd.to_datetime() function to convert the date column to a datetime object after the dataframe has been loaded. We store the results back in the date column of the original dataframe. Finally, we print the updated dataframe to the console to see the results.