Python Pandas - Extract the frequency object as a string from the DateTimeIndex

PythonServer Side ProgrammingProgramming

To extract the frequency object as a string from the DateTimeIndex, use the DateTimeIndex.freqstr property in Pandas.

At first, import the required libraries −

import pandas as pd

Create a DatetimeIndex with period 6 and frequency as D i.e. day −

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')

Display DateTimeIndex −

print("DateTimeIndex...\n", datetimeindex)

Display DateTimeIndex frequency as a string −

print("DateTimeIndex frequency as string...\n", datetimeindex.freqstr)

Example

Following is the code −

import pandas as pd

# DatetimeIndex with period 6 and frequency as D i.e. day
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Adelaide', freq='D')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# display DateTimeIndex frequency as a string
print("DateTimeIndex frequency as string...\n", datetimeindex.freqstr)

Output

This will produce the following code −

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+10:30', '2021-10-21 02:30:50+10:30',
'2021-10-22 02:30:50+10:30', '2021-10-23 02:30:50+10:30',
'2021-10-24 02:30:50+10:30', '2021-10-25 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='D')

DateTimeIndex frequency...
<Day>

DateTimeIndex frequency as string...
D
raja
Updated on 18-Oct-2021 12:42:45

Advertisements