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

Pandas provides various functions to convert the datetime object to string. The most common function to convert a datetime object to string is strftime(). This function allows you to specify the format of the output string using format codes. You can also use the astype() function to convert the datetime object to string. Other useful functions include to_string() and to_datetime() to convert between date and string formats. All these functions are extremely useful when dealing with date-related data.


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 .

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

x