Python Pandas - Convert Period to desired frequency


To convert Period to desired frequency, use the period.asfreq() method. Let’s say we will set to desired Hourly frequency using the ‘H’ specifier.

At first, import the required libraries −

import pandas as pd

The pandas.Period represents a period of time. Create two Period objects

period1 = pd.Period("2020-09-23 03:15:40")
period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, minute = 35)

Display the Period objects

print("Period1...\n", period1)
print("Period2...\n", period2)

Convert Period to desired frequency. We have set frequency as H i.e. Hourly frequency

res1 = period1.asfreq('H')
res2 = period2.asfreq('H')

Example

Following is the code

import pandas as pd

# The pandas.Period represents a period of time
# creating two Period objects
period1 = pd.Period("2020-09-23 03:15:40")
period2 = pd.Period(freq="D", year = 2021, month = 4, day = 16, hour = 2, minute = 35)

# display the Period objects
print("Period1...\n", period1)
print("Period2...\n", period2)

# Convert Period to desired frequency
# We have set frequency as H i.e. Hourly frequency
res1 = period1.asfreq('H')
res2 = period2.asfreq('H')

# Return the year from the two Period objects
print("\nResult after conversion from the 1st Period object ...\n", res1)
print("\nResult after conversion from the 2nd Period object...\n", res2)

Output

This will produce the following code

Period1...
2020-09-23 03:15:40
Period2...
2021-04-16

Result after conversion from the 1st Period object ...
2020-09-23 03:00

Result after conversion from the 2nd Period object...
2021-04-16 23:00

Updated on: 20-Oct-2021

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements