why inclusive is not working in pandas date_range function?

Viewed 55

pandas.date_range() to not return correct start and end timestamp when dates are set as a quarter string value.

start_date = '2021Q4'
end_date = '2024Q1'
dates=pd.date_range(start_date, end_date, freq='Q', inclusive='both').to_list()
dates
[Timestamp('2021-12-31 00:00:00', freq='Q-DEC'),
 Timestamp('2022-03-31 00:00:00', freq='Q-DEC'),
 Timestamp('2022-06-30 00:00:00', freq='Q-DEC'),
 Timestamp('2022-09-30 00:00:00', freq='Q-DEC'),
 Timestamp('2022-12-31 00:00:00', freq='Q-DEC'),
 Timestamp('2023-03-31 00:00:00', freq='Q-DEC'),
 Timestamp('2023-06-30 00:00:00', freq='Q-DEC'),
 Timestamp('2023-09-30 00:00:00', freq='Q-DEC'),
 Timestamp('2023-12-31 00:00:00', freq='Q-DEC')]
1 Answers

After I tried to fix your problem I found following solution:

The problem here is that date_range does not identify your strings correctly.

When you convert your "quarter"-strings to pandas.Period() and afterwards to pandas.Timestamp() this will work as expected:

import pandas as pd
from pprint import pprint

start_date = '2021Q4'
end_date = '2024Q1'

first_date_of_period  = pd.Period(start_date, 'Q').to_timestamp('D', 'S') # D for day, S for start
last_date_of_period = pd.Period(end_date, 'Q').to_timestamp('D', 'E') # D for day, E for end

print(first_date_of_period)
# >> 2021-10-01 00:00:00
print(last_date_of_period)
# >> 2024-03-31 23:59:59.999999999

dates=pd.date_range(start=first_date_of_period, end=last_date_of_period, freq='Q').to_list()
pprint(dates)
# >> [Timestamp('2021-12-31 00:00:00', freq='Q-DEC'),
# >>  Timestamp('2022-03-31 00:00:00', freq='Q-DEC'),
# >>  Timestamp('2022-06-30 00:00:00', freq='Q-DEC'),
# >>  Timestamp('2022-09-30 00:00:00', freq='Q-DEC'),
# >>  Timestamp('2022-12-31 00:00:00', freq='Q-DEC'),
# >>  Timestamp('2023-03-31 00:00:00', freq='Q-DEC'),
# >>  Timestamp('2023-06-30 00:00:00', freq='Q-DEC'),
# >>  Timestamp('2023-09-30 00:00:00', freq='Q-DEC'),
# >>  Timestamp('2023-12-31 00:00:00', freq='Q-DEC'),
# >>  Timestamp('2024-03-31 00:00:00', freq='Q-DEC')]

I used pandas v1.4.3 (last stable version).

Related