Skip to content

Python Pandas: How to Change the Pandas Datetime Format in Python

Learn how to use strftime() and pandas format codes to convert datetime objects into custom string formats like DD/MM/YYYY or 'July 15, 2024' for better data presentation.

Working with dates and times is a fundamental part of data analysis, and pandas provides powerful tools for handling datetime data. By default, pandas represents dates in the YYYY-MM-DD format (e.g., 2020-12-08 for December 8, 2020). However, you'll often need to display dates in a different format - whether it's DD/MM/YYYY, MM-DD-YYYY, or a more human-readable style like December 08, 2020.

In this guide, you'll learn how to change the datetime format in pandas using the strftime() method, along with practical examples covering the most common formatting scenarios.

Understanding strftime() and Format Codes

The strftime() method (short for string format time) converts datetime objects into formatted strings. You pass a format string composed of special directive codes, each representing a component of the date or time.

Here are the most commonly used format codes:

Code Description Example
%Y Full year (4 digits) 2024
%y Abbreviated year (2 digits) 24
%m Month as zero-padded number 01, 12
%B Full month name January
%b Abbreviated month name Jan
%d Day of the month (zero-padded) 01, 31
%H Hour (24-hour clock) 14
%I Hour (12-hour clock) 02
%M Minute 05
%S Second 09
%p AM/PM PM
%A Full weekday name Monday
%a Abbreviated weekday name Mon

Changing the Format of a Single Date String

The simplest case is converting a single date string to a different format using pd.to_datetime() and strftime().

import pandas as pd

date_sr = pd.to_datetime(pd.Series("2020-12-08"))

formatted = date_sr.dt.strftime('%d/%m/%Y')

print(formatted)

Output:

0    08/12/2020
dtype: object

The original 2020-12-08 (YYYY-MM-DD) is now displayed as 08/12/2020 (DD/MM/YYYY).

Formatting a Date Range Series

When working with a series of dates, strftime() applies the format to every element in the Series.

import pandas as pd

date_sr = pd.Series(pd.date_range('2019-12-31', periods=3, freq='M'))

date_sr.index = ['Day 1', 'Day 2', 'Day 3']

print("Original format:")
print(date_sr)
print()

formatted = date_sr.dt.strftime('%d,%m,%Y')

print("Formatted:")
print(formatted)

Output:

Original format:
Day 1   2019-12-31
Day 2   2020-01-31
Day 3   2020-02-29
dtype: datetime64[ns]

Formatted:
Day 1    31,12,2019
Day 2    31,01,2020
Day 3    29,02,2020
dtype: object

Common Date Format Examples

Below are several popular date formats you might need in real-world projects:

import pandas as pd

date_sr = pd.to_datetime(pd.Series("2024-07-15"))

print("DD-MM-YYYY:       ", date_sr.dt.strftime('%d-%m-%Y').iloc[0])

print("MM/DD/YYYY:       ", date_sr.dt.strftime('%m/%d/%Y').iloc[0])

print("Month DD, YYYY:   ", date_sr.dt.strftime('%B %d, %Y').iloc[0])

print("Day, Mon DD, YYYY:", date_sr.dt.strftime('%a, %b %d, %Y').iloc[0])

print("With time:        ", date_sr.dt.strftime('%d/%m/%Y %I:%M %p').iloc[0])

Output:

DD-MM-YYYY:        15-07-2024
MM/DD/YYYY:        07/15/2024
Month DD, YYYY:    July 15, 2024
Day, Mon DD, YYYY: Mon, Jul 15, 2024
With time:         15/07/2024 12:00 AM

Formatting Datetime Columns in a DataFrame

In practice, you'll most often reformat a datetime column inside a DataFrame - for example, before exporting data to CSV or displaying it in a report.

import pandas as pd

df = pd.DataFrame({
    'event': ['Launch', 'Update', 'Release'],
    'date': ['2024-01-15', '2024-06-20', '2024-12-01']
})

df['date'] = pd.to_datetime(df['date'])

df['date_formatted'] = df['date'].dt.strftime('%d %B %Y')

print(df)

Output:

     event       date    date_formatted
0   Launch 2024-01-15   15 January 2024
1   Update 2024-06-20      20 June 2024
2  Release 2024-12-01  01 December 2024

Formatting Dates with Timezone Information

If your datetime data includes timezone information, strftime() works the same way. You can also include the %Z directive to display the timezone name.

import pandas as pd

date_sr = pd.Series(pd.date_range(
    '2024-01-01', periods=3, freq='M', tz='Asia/Calcutta'
))

formatted = date_sr.dt.strftime('%d-%m-%Y %H:%M %Z')

print(formatted)

Output:

0    31-01-2024 00:00 IST
1    29-02-2024 00:00 IST
2    31-03-2024 00:00 IST
dtype: object

Parsing Custom Formats with pd.to_datetime()

Sometimes your source data uses a non-standard date format. Use the format parameter of pd.to_datetime() to parse it correctly, then reformat as needed.

import pandas as pd

raw_dates = pd.Series(['25/12/2024', '01/07/2023', '15/03/2022'])

parsed = pd.to_datetime(raw_dates, format='%d/%m/%Y')

reformatted = parsed.dt.strftime('%Y-%m-%d')

print(reformatted)

Output:

0    2024-12-25
1    2023-07-01
2    2022-03-15
dtype: object

Conclusion

Changing the datetime format in pandas comes down to two key tools:

  • pd.to_datetime() to parse date strings into proper datetime objects.
  • strftime() to convert datetime objects into any string format you need.

By combining these with pandas' format directive codes (%Y, %m, %d, %H, etc.), you can transform dates into virtually any representation, from compact numeric formats like 15-07-2024 to verbose human-readable ones like Monday, July 15, 2024.

Just remember to keep your original datetime column intact for calculations and use the formatted version only for display.

Navigation