How to Convert DateTime to String in Pandas (With Examples)


You can use the following basic syntax to convert a column from DateTime to string in pandas:

df['column_name'].dt.strftime('%Y-%m-%d')

The following example shows how to use this syntax in practice.

Example: Convert DateTime to String in Pandas

Suppose we have the following pandas DataFrame that shows the sales made by some store on four different days:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'day': pd.to_datetime(pd.Series(['20210101', '20210105',
                                                    '20210106', '20210109'])),
                   'sales': [1440, 1845, 2484, 2290]})

#view DataFrame
df

	       day     sales
0	2021-01-01	1440
1	2021-01-05	1845
2	2021-01-06	2484
3	2021-01-09	2290

We can use the dtypes function to view the data type of each column in the DataFrame:

#view data type of each column
df.dtypes

day      datetime64[ns]
sales             int64
dtype: object

We can see that the “day” column has a DateTime class.

To convert “day” into a string, we can use the following syntax:

#convert 'day' column to string
df['day'] = df['day'].dt.strftime('%Y-%m-%d')

#view updated DataFrame
df

	       day     sales
0	2021-01-01	1440
1	2021-01-05	1845
2	2021-01-06	2484
3	2021-01-09	2290

We can use the dtypes function again to verify that the “day” column is now a string:

#view data type of each column
df.dtypes

day      object
sales     int64
dtype: object

Note: You can find the complete documentation for the dt.strftime() function here.

Additional Resources

The following tutorials explain how to perform other common conversions in Python:

How to Convert Datetime to Date in Pandas
How to Convert Columns to DateTime in Pandas
How to Convert Timestamp to Datetime in Pandas

Leave a Reply

Your email address will not be published.