Home > Net >  Iterating over date range in python and setting the start and end date
Iterating over date range in python and setting the start and end date

Time:11-15

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.

CodePudding user response:

You can change the code slightly to,

import datetime

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

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


[(datetime.date(2022, 10, 31), datetime.date(2022, 11, 1)),
 (datetime.date(2022, 11, 1), datetime.date(2022, 11, 2)),
 (datetime.date(2022, 11, 2), datetime.date(2022, 11, 3)),
 (datetime.date(2022, 11, 3), datetime.date(2022, 11, 4))]

First item of the tuple is start date and the second item is end date.

CodePudding user response:

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
  • Related