Open In App
Related Articles

Pandas Series dt.strftime() Method | Change Date Format in Series

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The dt.strftime() method converts the datetime objects in the Pandas Series to a specified date format.

The function returns an index of formatted strings specified by date_format, which supports the same string format as the Python standard library.

Example

Python3

import pandas as pd
sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30',
            '2010-1-1 09:25', '2019-12-31 00:00'])
idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
sr.index = idx
sr = pd.to_datetime(sr)
result = sr.dt.strftime('% B % d, % Y, % r')
print(result)

                    

Output:

dt.strftime output example

Syntax

Syntax: Series.dt.strftime(Date_Format) 

Parameter 

  • date_format : Date format string (e.g. “%Y-%m-%d”) 

Returns: NumPy ndarray of formatted string

How to change the Date Format of DateTime objects in a Pandas Series

To change the date format of DateTime objects in a Pandas Series we use the dt.strftime method of the Pandas library in Python.

To understand it better, let us look at some example

Example:

Python3

# importing pandas as pd
import pandas as pd
 
# Creating the Series
sr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'M',
                            tz = 'Asia / Calcutta'))
 
# Creating the index
idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
 
# set the index
sr.index = idx
 
# Print the series
print(sr)

                    

Output:

datetime series created

Now we will use the Series dt.strftime() function to convert the dates in the series object to the specified format.

Python3

# convert to the given date format
result = sr.dt.strftime('% d % m % Y, % r')
 
# print the result
print(result)

                    

Output :

date format changed after dt.strftime

As we can see in the output, the dt.strftime() function has successfully converted the dates in the given series object to the specified format.



Last Updated : 06 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads