Search code examples
pythonpython-3.xpandaspython-datetimepython-dateutil

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.


Solution

  • 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