Pandas Series dt.strftime() Method | Change Date Format in Series
Last Updated :
06 Feb, 2024
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:
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
import pandas as pd
sr = pd.Series(pd.date_range( '2012-12-31 09:45' , periods = 5 , freq = 'M' ,
tz = 'Asia / Calcutta' ))
idx = [ 'Day 1' , 'Day 2' , 'Day 3' , 'Day 4' , 'Day 5' ]
sr.index = idx
print (sr)
|
Output:
Now we will use the Series dt.strftime() function to convert the dates in the series object to the specified format.
Python3
result = sr.dt.strftime( '% d % m % Y, % r' )
print (result)
|
Output :
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...