How to Convert Strings to Datetime in a pandas DataFrame
In this tutorial, you will learn how to convert strings to datetime in a DataFrame column.
TLDR solution
df['date'] = pd.to_datetime(df['date'], format='look at string')
Example 1: Convert Date Strings
Suppose, you have the following DataFrame.
import pandas as pd
data = {'date': ['01/15/2021', '02/15/2021', '03/15/2021']}
df = pd.DataFrame(data)
print(df)
print(df.dtypes)
date
0 01/15/2021
1 02/15/2021
2 03/15/2021
date object
dtype: object
The date column is of type object/string. Notice that the dates are formatted as mm/dd/yyyy.
Thus, to convert it to a pandas datetime object, use to_datetime function:
df['date'] = pd.to_datetime(df['date'], format='%m/%d/%Y')
print(df.dtypes)
date datetime64[ns]
dtype: object
Commonly Used Datetime Format Codes
| code | description | example |
|---|---|---|
| %Y | four-digit year | 2021 |
| %y | double-digit year | 21 |
| %m | double-digit month | 11 |
| %z | UTC offset | +0200 |
| %d | double-digit day | 30 |
| %H | double-digit hour 00-23 | 01 |
| %M | double-digit minute 00-59 | 22 |
| %S | double-digit seconds 00-59 | 59 |
Example 2: Convert Timestamp Strings
Suppose, you have the following DataFrame.
import pandas as pd
data = {'timestamp': ['2021-01-15 13:10:10', '2021-02-15 14:33:11', '2021-03-15 19:50:40']}
df = pd.DataFrame(data)
print(df)
print(df.dtypes)
timestamp
0 2021-01-15 13:10:10
1 2021-02-15 14:33:11
2 2021-03-15 19:50:40
timestamp object
dtype: object
Just as before, you can then convert it like this:
df['timestamp'] = pd.to_datetime(df['timestamp'], format='%Y-%m-%d %H:%M:%S')
print(df.dtypes)
date datetime64[ns]
dtype: object
That's it! You just converted a column of date strings to a datetime column.