Python’s iterators are great and all, but sometimes I really do want a C-style for loop – not a foreach loop. For example, I have a start date and an end date and I want to do something for every day in that range. I can do this with a while loop, of course:
current = start
while current <= finish:
do_stuff(current)
current += timedelta(1)
This works, but it’s 3 lines instead of 1 (in C or C-based languages) and I often find myself forgetting to write the incrementing line, especially if the loop body is quite complex. Is there a more elegant and less error-prone way of doing this in Python?
The elegant and Pythonic way to do it is to encapsulate the idea of a range of dates in its own generator, then use that generator in your code:
prints:
This is similar to the answer about
range, except that the built-inrangewon’t work with datetimes, so we have to create our own, but at least we can do it just once in an encapsulated way.