Python Pandas - Get the week of the year on the given Period

To get the week of the year on the given Period, use the period.weekofyear property. This property returns the week number (1-53) for any given date within a Period object.

Syntax

period.weekofyear

Where period is a pandas Period object representing a specific date or time period.

Creating Period Objects

First, import the required library and create Period objects using different methods −

import pandas as pd

# Creating Period objects using different approaches
period1 = pd.Period("2020-09-23")
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)
Period1...
2020-09-23
Period2...
2021-04-16

Getting Week of Year

Use the weekofyear property to extract the week number from Period objects −

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)

# Get the week of the year from Period objects
week1 = period1.weekofyear
week2 = period2.weekofyear

print("Week of the year from Period1:", week1)
print("Week of the year from Period2:", week2)
Week of the year from Period1: 39
Week of the year from Period2: 15

Complete Example

Here's a comprehensive example showing multiple dates and their corresponding week numbers −

import pandas as pd

# Create multiple Period objects for different dates
dates = ["2020-01-01", "2020-07-15", "2020-12-31", "2021-06-20"]
periods = [pd.Period(date) for date in dates]

# Display each period and its week of year
for i, period in enumerate(periods):
    print(f"Date: {period} ? Week: {period.weekofyear}")
Date: 2020-01-01 ? Week: 1
Date: 2020-07-15 ? Week: 29
Date: 2020-12-31 ? Week: 53
Date: 2021-06-20 ? Week: 24

Key Points

  • Week numbers range from 1 to 53 depending on the year
  • The first week of the year contains January 1st
  • Works with any Period object regardless of frequency (daily, monthly, etc.)
  • Returns an integer representing the week number

Conclusion

The weekofyear property provides a simple way to extract week numbers from pandas Period objects. This is useful for time-based analysis and grouping data by weeks within a year.

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

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements