To convert a column of strings representing dates to a column of datetimes in pandas, you can use the pd.to_datetime() function.

import pandas as pd

df = pd.DataFrame({
    "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"]
})

df["date"] = pd.to_datetime(df["date"])

print(df["date"])

#Output:
0   2021-09-30
1   2021-12-31
2   2022-03-31
3   2022-06-30
4   2022-09-30
5   2022-12-31
Name: date, dtype: datetime64[ns]

When working with different types of data, the ability to easily be able to convert variables into variables of other types is valuable.

One such case is converting strings to datetimes in a pandas DataFrame.

To convert a column of strings representing dates to a column of datetimes in pandas, you can use the pd.to_datetime() function.

pd.to_datetime() convert a scalar, array-like, Series or DataFrame/dict-like to a pandas datetime object.

For valid string formats, pd.to_datetime() will convert a “date” string into a datetime. For example, if my strings look like “YYYY-MM-DD”, then pd.to_datetime() will convert this into a datetime formatted like “YYYY-MM-DD”.

Below is a simple example showing you how to use pd.datetime() in Python to convert a column of strings to a datetime column in pandas.

import pandas as pd

df = pd.DataFrame({
    "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"]
})

df["date"] = pd.to_datetime(df["date"])

print(df["date"])

#Output:
0   2021-09-30
1   2021-12-31
2   2022-03-31
3   2022-06-30
4   2022-09-30
5   2022-12-31
Name: date, dtype: datetime64[ns]

Hopefully this article has been useful for you to learn how to pd.to_datetime() to convert a column of strings to datetime in pandas.

Categorized in:

Python,

Last Update: March 1, 2024