Python Pandas - Extract month number from the DateTimeIndex with specific time series frequency

To extract month numbers from a DateTimeIndex with specific time series frequency, use the DateTimeIndex.month property. This returns integer values from 1 to 12 representing January through December.

Creating a DateTimeIndex

First, let's create a DateTimeIndex with monthly frequency ?

import pandas as pd

# DateTimeIndex with period 6 and frequency as M (month end)
# Timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-09-24 02:35:55', periods=6, tz='Australia/Sydney', freq='M')

print("DateTimeIndex...")
print(datetimeindex)
DateTimeIndex...
DatetimeIndex(['2021-09-30 02:35:55+10:00', '2021-10-31 02:35:55+11:00',
               '2021-11-30 02:35:55+11:00', '2021-12-31 02:35:55+11:00',
               '2022-01-31 02:35:55+11:00', '2022-02-28 02:35:55+11:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='M')

Extracting Month Numbers

Use the month property to extract month numbers where January=1, February=2, ..., December=12 ?

import pandas as pd

# Create DateTimeIndex with monthly frequency
datetimeindex = pd.date_range('2021-09-24 02:35:55', periods=6, tz='Australia/Sydney', freq='M')

# Display DateTimeIndex
print("DateTimeIndex...")
print(datetimeindex)

# Display frequency
print("\nDateTimeIndex frequency...")
print(datetimeindex.freq)

# Extract month numbers
print("\nMonth numbers...")
print(datetimeindex.month)
DateTimeIndex...
DatetimeIndex(['2021-09-30 02:35:55+10:00', '2021-10-31 02:35:55+11:00',
               '2021-11-30 02:35:55+11:00', '2021-12-31 02:35:55+11:00',
               '2022-01-31 02:35:55+11:00', '2022-02-28 02:35:55+11:00'],
              dtype='datetime64[ns, Australia/Sydney]', freq='M')

DateTimeIndex frequency...
<MonthEnd>

Month numbers...
Int64Index([9, 10, 11, 12, 1, 2], dtype='int64')

Key Points

The month property returns:

  • Integer values from 1 to 12
  • An Int64Index object with the same length as the original DateTimeIndex
  • Month numbers based on the actual dates, not the frequency

Conclusion

The DateTimeIndex.month property provides a simple way to extract month numbers from datetime data. This is particularly useful for time series analysis and grouping operations by month.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements