Python Pandas - Get the year from the Period object

To get the year from the Period object, use the period.year property. A pandas Period represents a specific span of time with a given frequency.

Importing Required Library

First, import pandas to work with Period objects ?

import pandas as pd

Creating Period Objects

You can create Period objects using different approaches ?

import pandas as pd

# Create Period from date string
period1 = pd.Period("2020-09-23")

# Create Period with specific frequency and date components
period2 = pd.Period(freq="D", year=2021, month=4, day=16, hour=2, minute=35)

print("Period1:", period1)
print("Period2:", period2)
Period1: 2020-09-23
Period2: 2021-04-16

Extracting Year from Period Objects

Use the .year property to extract the year component ?

import pandas as pd

# Create Period objects
period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year=2021, month=4, day=16, hour=2, minute=35)

# Extract years
year1 = period1.year
year2 = period2.year

print("Year from Period1:", year1)
print("Year from Period2:", year2)
print("Year type:", type(year1))
Year from Period1: 2020
Year from Period2: 2021
Year type: <class 'int'>

Working with Different Frequencies

The year property works with various Period frequencies ?

import pandas as pd

# Different frequency Period objects
monthly = pd.Period("2023-07", freq="M")
quarterly = pd.Period("2023Q2", freq="Q")
yearly = pd.Period("2024", freq="Y")

print("Monthly period:", monthly, "- Year:", monthly.year)
print("Quarterly period:", quarterly, "- Year:", quarterly.year)
print("Yearly period:", yearly, "- Year:", yearly.year)
Monthly period: 2023-07 - Year: 2023
Quarterly period: 2023Q2 - Year: 2023
Yearly period: 2024 - Year: 2024

Conclusion

The .year property provides a simple way to extract the year component from any pandas Period object. This property returns an integer representing the year, regardless of the Period's frequency.

Updated on: 2026-03-26T17:44:30+05:30

601 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements