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

codedescriptionexample
%Yfour-digit year2021
%ydouble-digit year21
%mdouble-digit month11
%zUTC offset+0200
%ddouble-digit day30
%Hdouble-digit hour 00-2301
%Mdouble-digit minute 00-5922
%Sdouble-digit seconds 00-5959

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.