Python Pandas - Create a PeriodIndex and get the day of the month

To create a PeriodIndex, use the pandas.PeriodIndex() method. Get the days of the month using the PeriodIndex.daysinmonth property.

A PeriodIndex is an immutable ndarray holding ordinal values that represent regular periods in time. It's particularly useful for time series analysis when you need to work with periods rather than timestamps.

Creating a PeriodIndex

At first, import the required libraries ?

import pandas as pd

Create a PeriodIndex object. We set the frequency using the "freq" parameter ?

import pandas as pd

# Create a PeriodIndex object with daily frequency
periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
                             '2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

# Display PeriodIndex object
print("PeriodIndex...\n", periodIndex)
PeriodIndex...
 PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'], dtype='period[D]')

Getting Days in Month

Display days in the specific month from the PeriodIndex object using the daysinmonth property ?

import pandas as pd

periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
                             '2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

# Display frequency information
print("PeriodIndex frequency...\n", periodIndex.freq)

# Display the month number (1 = January, 2 = February ... 12 = December)
print("\nMonth number...\n", periodIndex.month)

# Display days in the specific month from the PeriodIndex object
print("\nDays of the specific month from the PeriodIndex...\n", periodIndex.daysinmonth)
PeriodIndex frequency...
 <Day>

Month number...
 Int64Index([7, 10, 11, 9, 3, 6], dtype='int64')

Days of the specific month from the PeriodIndex...
 Int64Index([31, 31, 30, 30, 31, 30], dtype='int64')

Understanding the Results

The output shows that:

  • July (month 7) has 31 days
  • October (month 10) has 31 days
  • November (month 11) has 30 days
  • September (month 9) has 30 days
  • March (month 3) has 31 days
  • June (month 6) has 30 days

Conclusion

The PeriodIndex.daysinmonth property provides an easy way to get the number of days in each month for dates in a PeriodIndex. This is useful for calendar calculations and time series analysis.

Updated on: 2026-03-26T18:00:32+05:30

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements