1

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.

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.