Iterating over date range in python and setting the start and end date

Issue

I know this question is a repeated one. But what I am trying to do is, I want to iterate through a date range and for each iteration i need to set the fromDate and toDate.

for ex:
If I give the date range as startDate = ‘2022-10-31’
and endDate = ‘2022-11-04’

and for each iteration fromDate = ‘2022-10-31’ and toDate = ‘2022-11-01’
next iteration fromDate = ‘2022-11-01’ and endDate = ‘2022-11-02’ and so on.

I did some research and got to know how to iterate through dateRange.
sample code:

import datetime
start_date = datetime.date(2022, 10, 31)
end_date   = datetime.date(2022, 11, 04)

dates_2011_2013 = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]

This just prints the incremented dates in the date Range. Am new to Python language. Any help is appreciated.

Thank you.

Solution

I want to iterate through a date range

another option is using while:

while start_date < end_date:
    print(start_date, start_date + datetime.timedelta(1))
    start_date += datetime.timedelta(1)

'''
2022-10-31 2022-11-01
2022-11-01 2022-11-02
2022-11-02 2022-11-03
2022-11-03 2022-11-04

Answered By – SergFSM

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.