Iterating through a Date Range

The below code allows us to iterate through a date range with a specified interval of days

Importing necessary packages

In [1]:
from datetime import date, timedelta, datetime

Creating the function

In [2]:
def dateiteration(start_date,end_date,day_range):
    
    #converting string to date formats
    start_date = datetime.strptime(start_date, '%d/%m/%y')
    end_date = datetime.strptime(end_date, '%d/%m/%y')
    day_range = timedelta(days=day_range)
    
    #creating a while loop to print out start dates
    while start_date < end_date:
        print(("From " + "{date.day:02}/{date.month:02}/{date.year}".
               format(date=start_date)) 
              +
              (" to " + "{date.day:02}/{date.month:02}/{date.year}".
               format(date=start_date+day_range-timedelta(days=1))))
        start_date += day_range

Calling out the function

In [3]:
#input start date, end date and interval (format: dd/mm/yy)
dateiteration('01/05/19','18/05/20',45)
From 01/05/2019 to 14/06/2019
From 15/06/2019 to 29/07/2019
From 30/07/2019 to 12/09/2019
From 13/09/2019 to 27/10/2019
From 28/10/2019 to 11/12/2019
From 12/12/2019 to 25/01/2020
From 26/01/2020 to 10/03/2020
From 11/03/2020 to 24/04/2020
From 25/04/2020 to 08/06/2020

Author: Amandeep Saluja