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

PythonServer Side ProgrammingProgramming

To format and return the string representation of the Period object, use the period.strftime() method. With that, set the format specifiers as an argument like strftime('%d-%b-%Y').

At first, import the required libraries −

import pandas as pd

The pandas.Period represents a period of time. Creating a Period object

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

Display the Period object

print("Period...\n", period)

Display the formatted string representation

print("\nString representation (format)...\n", period.strftime('%d-%b-%Y'))

Example

Following is the code

import pandas as pd

# The pandas.Period represents a period of time
# Creating a Period object
period = pd.Period(freq="S", year = 2021, month = 9, day = 18, hour = 8, minute = 20, second = 45)

# display the Period object
print("Period...\n", period)

# display the result
print("\nString representation (format)...\n", period.strftime('%d-%b-%Y'))

# display the result
print("\nString representation (format with different directives)...\n",
period.strftime('%b. %d, %Y was a %A'))

Output

This will produce the following code

Period...
2021-09-18 08:20:45

String representation (format)...
18-Sep-2021

String representation (format with different directives)...
Sep. 18, 2021 was a Saturday
raja
Updated on 20-Oct-2021 06:44:50

Advertisements