Python Pandas - Convert given Timestamp to Period


To convert given Timestamp to Period, use the timestamp.to_period() method. Within that, set the frequency using the freq parameter.

At first, import the required libraries −

import pandas as pd

Set the timestamp object in Pandas

timestamp = pd.Timestamp('2021-09-14T15:12:34.261811624')

Now, convert timestamp to Period. We have set the frequency as Month using the "freq" parameter with value 'M'

timestamp.to_period(freq='M')

Example

Following is the code

import pandas as pd

# set the timestamp object in Pandas
timestamp = pd.Timestamp('2021-09-14T15:12:34.261811624')

# display the Timestamp
print("Timestamp...\n", timestamp)

# convert timestamp to Period
# we have set the frequency as Month using the "freq" parameter with value 'M'
print("\nTimestamp to Period...\n", timestamp.to_period(freq='M'))

Output

This will produce the following code

Timestamp...
 2021-09-14 15:12:34.261811624

Timestamp to Period...
2021-09

Updated on: 13-Oct-2021

619 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements