Python Pandas - Get the Day of the year from Period object

To get the day of the year from a Period object, use the period.dayofyear property. This returns an integer between 1-365 for regular years and 1-366 for leap years.

What is a Period Object?

The pandas.Period represents a specific period of time with a defined frequency. It's useful for time-based data analysis and operations.

Creating Period Objects

You can create Period objects in multiple ways ?

import pandas as pd

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

# Create Period with explicit parameters
period2 = pd.Period(freq="D", year=2021, month=7, day=16, hour=2, minute=35)

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

Getting Day of Year

Use the dayofyear property to extract the day number within the year ?

import pandas as pd

# Create Period objects
period1 = pd.Period("2020-09-23")  # Leap year
period2 = pd.Period("2021-07-16")  # Regular year

# Get day of year
day_of_year_1 = period1.dayofyear
day_of_year_2 = period2.dayofyear

print(f"September 23, 2020 is day {day_of_year_1} of the year")
print(f"July 16, 2021 is day {day_of_year_2} of the year")

# Additional examples
new_year = pd.Period("2021-01-01")
year_end = pd.Period("2021-12-31")

print(f"January 1st is day {new_year.dayofyear}")
print(f"December 31st is day {year_end.dayofyear}")
September 23, 2020 is day 267 of the year
July 16, 2021 is day 197 of the year
January 1st is day 1
December 31st is day 365

Leap Year Consideration

The dayofyear property automatically handles leap years ?

import pandas as pd

# Compare leap year vs regular year
leap_year_feb29 = pd.Period("2020-02-29")  # 2020 is leap year
regular_year_dec31 = pd.Period("2021-12-31")  # 2021 is regular year
leap_year_dec31 = pd.Period("2020-12-31")  # 2020 is leap year

print(f"Feb 29, 2020 (leap year): day {leap_year_feb29.dayofyear}")
print(f"Dec 31, 2021 (regular): day {regular_year_dec31.dayofyear}")
print(f"Dec 31, 2020 (leap year): day {leap_year_dec31.dayofyear}")
Feb 29, 2020 (leap year): day 60
Dec 31, 2021 (regular): day 365
Dec 31, 2020 (leap year): day 366

Conclusion

The dayofyear property provides an easy way to get the ordinal day number from any Period object. It automatically handles leap years and returns values from 1 to 366 depending on the year type.

Updated on: 2026-03-26T16:26:35+05:30

254 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements