Python Pandas - Detect the frequency of the given DatetimeIndex object

To detect the frequency of a given DatetimeIndex object, use the DatetimeIndex.inferred_freq property. This property automatically infers the frequency pattern from the datetime values.

Creating a DatetimeIndex

First, let's create a DatetimeIndex with a specific frequency ?

import pandas as pd

# Create DatetimeIndex with 5 periods and 3-year frequency
# Using Australia/Adelaide timezone
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=5, tz='Australia/Adelaide', freq='3Y')

print("DateTimeIndex...")
print(datetimeindex)
DateTimeIndex...
DatetimeIndex(['2021-12-31 02:30:50+10:30', '2024-12-31 02:30:50+10:30',
               '2027-12-31 02:30:50+10:30', '2030-12-31 02:30:50+10:30',
               '2033-12-31 02:30:50+10:30'],
              dtype='datetime64[ns, Australia/Adelaide]', freq='3A-DEC')

Detecting Frequency

Use the freq property to get the original frequency and inferred_freq to detect the pattern ?

import pandas as pd

datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=5, tz='Australia/Adelaide', freq='3Y')

# Display original frequency
print("Original frequency:", datetimeindex.freq)

# Detect inferred frequency
print("Inferred frequency:", datetimeindex.inferred_freq)
Original frequency: <3 * YearEnds: month=12>
Inferred frequency: 3A-DEC

Working with Different Frequencies

Let's see how frequency detection works with monthly and daily patterns ?

import pandas as pd

# Monthly frequency
monthly_index = pd.date_range('2023-01-01', periods=6, freq='M')
print("Monthly DatetimeIndex:")
print("Inferred frequency:", monthly_index.inferred_freq)

# Daily frequency  
daily_index = pd.date_range('2023-01-01', periods=7, freq='D')
print("\nDaily DatetimeIndex:")
print("Inferred frequency:", daily_index.inferred_freq)
Monthly DatetimeIndex:
Inferred frequency: M

Daily DatetimeIndex:
Inferred frequency: D

Key Points

  • freq property returns the original frequency object used during creation
  • inferred_freq property returns a string representing the detected frequency pattern
  • Frequency detection works automatically based on the spacing between datetime values
  • Common frequency codes: 'D' (daily), 'M' (monthly), 'A' (annual), 'H' (hourly)

Conclusion

The inferred_freq property automatically detects frequency patterns in DatetimeIndex objects. Use freq for the original frequency object and inferred_freq for the string representation of the detected pattern.

Updated on: 2026-03-26T17:12:46+05:30

249 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements