Python Pandas - Format and return the string representation of the Period object

To format and return the string representation of a Period object in Pandas, use the strftime() method. This method accepts format specifiers to customize the output format, such as '%d-%b-%Y' for day-month-year representation.

What is a Period Object?

A Pandas Period represents a specific time span with a defined frequency. It can represent anything from seconds to years, depending on the frequency parameter specified.

Creating a Period Object

First, let's create a Period object with second-level frequency ?

import pandas as pd

# Create a Period object with second frequency
period = pd.Period(freq="S", year=2021, month=9, day=18, hour=8, minute=20, second=45)
print("Period object:", period)
Period object: 2021-09-18 08:20:45

Using strftime() for Custom Formatting

The strftime() method allows you to format the Period object using standard datetime format codes ?

import pandas as pd

period = pd.Period(freq="S", year=2021, month=9, day=18, hour=8, minute=20, second=45)

# Basic date format
basic_format = period.strftime('%d-%b-%Y')
print("Basic format:", basic_format)

# Detailed format with day name
detailed_format = period.strftime('%b. %d, %Y was a %A')
print("Detailed format:", detailed_format)

# Time format
time_format = period.strftime('%H:%M:%S on %Y-%m-%d')
print("Time format:", time_format)
Basic format: 18-Sep-2021
Detailed format: Sep. 18, 2021 was a Saturday
Time format: 08:20:45 on 2021-09-18

Common Format Specifiers

Format Code Description Example
%Y 4-digit year 2021
%y 2-digit year 21
%m Month as number 09
%b Abbreviated month Sep
%B Full month name September
%d Day of month 18
%A Full weekday name Saturday

Multiple Format Examples

Here are various formatting options for the same Period object ?

import pandas as pd

period = pd.Period(freq="D", year=2021, month=9, day=18)

formats = {
    'ISO format': '%Y-%m-%d',
    'US format': '%m/%d/%Y', 
    'European format': '%d.%m.%Y',
    'Long format': '%A, %B %d, %Y',
    'Short format': '%d %b %y'
}

for name, fmt in formats.items():
    result = period.strftime(fmt)
    print(f"{name}: {result}")
ISO format: 2021-09-18
US format: 09/18/2021
European format: 18.09.2021
Long format: Saturday, September 18, 2021
Short format: 18 Sep 21

Conclusion

The strftime() method provides flexible formatting options for Period objects using standard datetime format codes. Use it to convert Period objects into human-readable strings in any desired format for reports, displays, or data export.

Updated on: 2026-03-26T17:45:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements