Iterating through a range of dates in Python Iterating through a range of dates in Python python python

Iterating through a range of dates in Python


Why are there two nested iterations? For me it produces the same list of data with only one iteration:

for single_date in (start_date + timedelta(n) for n in range(day_count)):    print ...

And no list gets stored, only one generator is iterated over. Also the "if" in the generator seems to be unnecessary.

After all, a linear sequence should only require one iterator, not two.

Update after discussion with John Machin:

Maybe the most elegant solution is using a generator function to completely hide/abstract the iteration over the range of dates:

from datetime import date, timedeltadef daterange(start_date, end_date):    for n in range(int((end_date - start_date).days)):        yield start_date + timedelta(n)start_date = date(2013, 1, 1)end_date = date(2015, 6, 2)for single_date in daterange(start_date, end_date):    print(single_date.strftime("%Y-%m-%d"))

NB: For consistency with the built-in range() function this iteration stops before reaching the end_date. So for inclusive iteration use the next day, as you would with range().


This might be more clear:

from datetime import date, timedeltastart_date = date(2019, 1, 1)end_date = date(2020, 1, 1)delta = timedelta(days=1)while start_date <= end_date:    print(start_date.strftime("%Y-%m-%d"))    start_date += delta


Use the dateutil library:

from datetime import datefrom dateutil.rrule import rrule, DAILYa = date(2009, 5, 30)b = date(2009, 6, 9)for dt in rrule(DAILY, dtstart=a, until=b):    print dt.strftime("%Y-%m-%d")

This python library has many more advanced features, some very useful, like relative deltas—and is implemented as a single file (module) that's easily included into a project.


matomo