How to Convert Datetime to String in Pandas

Sharing is caring!

Last Updated on March 1, 2022 by Jay

In this short tutorial, we’ll learn how to convert a DateTime column to String in pandas.

Sample Dataset

We’ll use the below simple dataset that contains dates, and daily stock prices. Let’s also first convert the String data into DateTime for the date column.

import pandas as pd

df = pd.DataFrame({'date':['2021-12-01', '2022-01-01','2022-02-01','2022-03-01','2022-04-01','2022-05-01'],
                   'open':[100, 101, 102, 103, 104, 105],
                   'high':[1000, 1001, 1002, 1003, 1004, 1005],
                   'low':[0, 1,2,3,4,5],
                   'close':[200, 201,202,203,204,205]})

#convert string to datetime
df['date'] = pd.to_datetime(df['date'])

	      date	open	high	low	close
0	2021-12-01	100	1000	0	200
1	2022-01-01	101	1001	1	201
2	2022-02-01	102	1002	2	202
3	2022-03-01	103	1003	3	203
4	2022-04-01	104	1004	4	204
5	2022-05-01	105	1005	5	205

Convert Datetime to String Using Pandas strftime()

strftime() is actually a method from the datetime class. However, we can access this function with pandas’ dt accessor. An accessor essentially extends pandas’ functionalities. In this case, dt gives access to the datetime functions.

The below code shows we can get just the “date” portion of the datetime data using the .dt accessor.

df['date'].dt.date

0    2021-12-01
1    2022-01-01
2    2022-02-01
3    2022-03-01
4    2022-04-01
5    2022-05-01
Name: date, dtype: object

To convert the datetime column to string, we can call the dt.strftime() function.

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

0    2021-12-01
1    2022-01-01
2    2022-02-01
3    2022-03-01
4    2022-04-01
5    2022-05-01
Name: date, dtype: object

df['date'].dt.strftime('%Y-%m-%d')[0]
'2021-12-01'

We can also use other delimiters to separate the year, month, and day like the below.

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

0    2021..12..01
1    2022..01..01
2    2022..02..01
3    2022..03..01
4    2022..04..01
5    2022..05..01
Name: date, dtype: object

Convert Datetime to String Using .astype()

Another way to convert datetime to string is to use the .astype() method. The below shows that both str and ‘string’ will work as the argument.

df['date'].astype(str)
0    2021-12-01
1    2022-01-01
2    2022-02-01
3    2022-03-01
4    2022-04-01
5    2022-05-01
Name: date, dtype: object


df['date'].astype('string')
0    2021-12-01
1    2022-01-01
2    2022-02-01
3    2022-03-01
4    2022-04-01
5    2022-05-01
Name: date, dtype: string

Note the .astype() simply converts a dataframe column to string representation and doesn’t allow for other manipulation such as choosing our own delimiters. This method is “you get what you see”.

Additional Resources

How to Convert Column to Datetime in Pandas

How to Filter Pandas Dataframe by Date

Leave a Reply

Your email address will not be published. Required fields are marked *