Table of Contents
To convert a date string in the format YYYY-MM-DD to a datetime data type, I need to use the datetime library and specify the format of the string so that it can be properly interpreted and converted into a datetime data type. To do this, I will use the datetime.strptime method, passing in the date string as the first argument and the format string as the second argument. This will allow me to convert the date string into a datetime object.
You can use the following methods to convert a string column to a datetime format in a pandas DataFrame:
Method 1: Convert One String Column to Datetime
df['col1'] = pd.to_datetime(df['col1'])
Method 2: Convert Multiple String Columns to Datetime
df[['col1', 'col2']] = df[['col1', 'col2']].apply(pd.to_datetime)
The following examples show how to use each of these methods in practice with the following pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'task': ['A', 'B', 'C', 'D'], 'due_date': ['4-15-2022', '5-19-2022', '6-14-2022', '10-24-2022'], 'comp_date': ['4-14-2022', '5-23-2022', '6-24-2022', '10-7-2022']}) #view DataFrame print(df) task due_date comp_date 0 A 2022-04-15 2022-04-14 1 B 2022-05-19 2022-05-23 2 C 2022-06-14 2022-06-24 3 D 2022-10-24 2022-10-07 #view data type of each column print(df.dtypes) task object due_date object comp_date object dtype: object
We can see that each column in the DataFrame currently has a data type of object, i.e. a string.
Example 1: Convert One String Column to Datetime
We can use the following syntax to convert the due_date column from a string to a datetime:
#convert due_date column to datetime
df['due_date'] = pd.to_datetime(df['due_date'])
#view updated DataFrame
print(df)
task due_date comp_date
0 A 2022-04-15 4-14-2022
1 B 2022-05-19 5-23-2022
2 C 2022-06-14 6-24-2022
3 D 2022-10-24 10-7-2022
#view data type of each column
print(df.dtypes)
task object
due_date datetime64[ns]
comp_date object
dtype: object
We can see that the due_date column has been converted to a datetime while all other columns have remain unchanged.
Example 2: Convert Multiple String Columns to Datetime
We can use the following syntax to convert both the due_date and comp_date columns from a string to a datetime:
#convert due_date and comp_date columns to datetime
df[['due_date', 'comp_date']] = df[['due_date', 'comp_date']].apply(pd.to_datetime)
#view updated DataFrame
print(df)
task due_date comp_date
0 A 2022-04-15 2022-04-14
1 B 2022-05-19 2022-05-23
2 C 2022-06-14 2022-06-24
3 D 2022-10-24 2022-10-07
#view data type of each column
print(df.dtypes)
task object
due_date datetime64[ns]
comp_date datetime64[ns]
dtype: object
We can see that the due_date and comp_date columns have both been converted from a string to a datetime.
Note: You can find the complete documentation for the pandas to_datetime() function .