How to convert a column of strings to datetime in a Pandas DataFrame?
Published on Aug. 22, 2023, 12:19 p.m.
To convert a column of strings to datetime in a Pandas DataFrame, you can use the pandas.to_datetime()
method. Here is an example:
import pandas as pd
# Create a sample DataFrame with a column of strings
data = {'date': ['2021-12-10', '2022-01-05', '2022-02-15']}
df = pd.DataFrame(data)
# Convert the 'date' column to datetime format
df['date'] = pd.to_datetime(df['date'])
# Print the updated DataFrame
print(df)
This will output the following DataFrame with the ‘date’ column in datetime format:
date
0 2021-12-10
1 2022-01-05
2 2022-02-15
You can also specify the format of the strings using the format
parameter. For example, if your strings are in the ‘yyyymmdd’ format, you can modify the code like so:
df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')
This will convert the ‘date’ column from the ‘yyyymmdd’ string format to datetime format.