Python Pandas - Get the total number of days of the month that the Period falls in

To get the total number of days of the month that a Period falls in, use the period.daysinmonth property in Pandas. This property returns an integer representing the total days in that specific month and year.

Syntax

period.daysinmonth

Where period is a Pandas Period object.

Creating Period Objects

First, let's create Period objects to demonstrate the daysinmonth property ?

import pandas as pd

# Create Period objects using different methods
period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year=2021, month=2, day=14, hour=2, minute=35)
period3 = pd.Period("2020-02-15")  # Leap year February

# Display the Period objects
print("Period1...\n", period1)
print("Period2...\n", period2)
print("Period3...\n", period3)
Period1...
2020-09-23
Period2...
2021-02-14
Period3...
2020-02-15

Getting Days in Month

Now let's extract the total days for each month using the daysinmonth property ?

import pandas as pd

# Create Period objects
period1 = pd.Period("2020-09-23")  # September 2020
period2 = pd.Period("2021-02-14")  # February 2021 (non-leap year)
period3 = pd.Period("2020-02-15")  # February 2020 (leap year)

# Get days in month for each Period
days1 = period1.daysinmonth
days2 = period2.daysinmonth
days3 = period3.daysinmonth

print("September 2020 has", days1, "days")
print("February 2021 has", days2, "days")
print("February 2020 has", days3, "days")
September 2020 has 30 days
February 2021 has 28 days
February 2020 has 29 days

Key Points

  • The daysinmonth property automatically handles leap years
  • It works with any valid Period object regardless of frequency
  • The property returns the total days for the month containing the Period
  • Useful for date calculations and month-end processing

Comparison of Different Months

Month Regular Year Leap Year
January 31 31
February 28 29
September 30 30

Conclusion

The daysinmonth property provides an easy way to get the total days in a month for any Period object. It automatically handles leap years and different month lengths, making it ideal for date-related calculations.

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

760 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements