sabari
sabari

Reputation: 33

python get the quarterly dates from a date range

python get the quarterly dates from a date range

example :

start date = 01/04/2020
end date = 01/04/2021

Here I need to get the Quaternary dates from this date range.

Upvotes: 3

Views: 6405

Answers (3)

gushart
gushart

Reputation: 161

pd.date_range(start date, end date, freq='3m').to_period('Q')

Upvotes: 1

Máté Farkas
Máté Farkas

Reputation: 32

With pure Python:

import datetime

start_date_str = "01/04/2020"
end_date_str = "01/04/2021"

start_date = datetime.datetime.strptime(start_date_str, "%d/%m/%Y").date()
end_date = datetime.datetime.strptime(end_date_str, "%d/%m/%Y").date()

print(f"Quarters within {start_date_str} and {end_date_str}:")
start_of_quarter = start_date
while True:
    far_future = start_of_quarter + datetime.timedelta(days=93)
    start_of_next_quarter = far_future.replace(day=1)
    end_of_quarter = start_of_next_quarter - datetime.timedelta(days=1)
    if end_of_quarter > end_date:
        break
    print(f"\t{start_of_quarter:%d/%m/%Y} - {end_of_quarter:%d/%m/%Y}")
    start_of_quarter = start_of_next_quarter

Upvotes: -2

luigigi
luigigi

Reputation: 4215

Try:

start_date = "01/04/2020"
end_date = "01/04/2021"
pd.date_range(start_date, end_date, freq='Q')

DatetimeIndex(['2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31'], dtype='datetime64[ns]', freq='Q-DEC')

Upvotes: 8

Related Questions