Python Pandas - Extract the quarter of the date from the DateTimeIndex with specific time series frequency


To extract the quarter of the date from the DateTimeIndex with specific time series frequency, use the DateTimeIndex.quarter.

At first, import the required libraries −

import pandas as pd

Create a DatetimeIndex with period 6 and frequency as M i.e. Month. The timezone is Australia/Sydney −

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

Display DateTimeIndex frequency −

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

Get the quarter of the date −

print("\nGet the quarter of the date..\n",datetimeindex.quarter)

Result is based on the following quarters of an year −

Quarter 1 = 1st January to 31st March
Quarter 2 = 1st April to 30th June
Quarter 3 = 1st July to 30th September
Quarter 4 = 1st October to 31st December

Example

Following is the code −

import pandas as pd

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

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

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

# Get the quarter of the date
# Result is based on the following quarters of an year:
# Quarter 1 = 1st January to 31st March
# Quarter 2 = 1st April to 30th June
# Quarter 3 = 1st July to 30th September
# Quarter 4 = 1st October to 31st December
print("\nGet the quarter of the date..\n",datetimeindex.quarter)

Output

This will produce the following code −

DateTimeIndex...
DatetimeIndex(['2021-10-31 02:30:50+11:00', '2021-12-31 02:30:50+11:00',
'2022-02-28 02:30:50+11:00', '2022-04-30 02:30:50+10:00',
'2022-06-30 02:30:50+10:00', '2022-08-31 02:30:50+10:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='2M')
DateTimeIndex frequency...
<2 * MonthEnds>

Get the quarter of the date..
Int64Index([4, 4, 1, 2, 2, 3], dtype='int64')

Updated on: 18-Oct-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements