Iterate over a range of dates, [begin, end), day by day. By using datetime objects, rather than date object, it is possible to iterate over smaller time-granularities if desired.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
from datetime import timedelta def daterange(begin, end, delta = timedelta(1)): """Form a range of dates and iterate over them. Arguments: begin -- a date (or datetime) object; the beginning of the range. end -- a date (or datetime) object; the end of the range. delta -- (optional) a timedelta object; how much to step each iteration. Default step is 1 day. Usage: """ if not isinstance(delta, timedelta): delta = timedelta(delta) ZERO = timedelta(0) if begin < end: if delta <= ZERO: raise StopIteration test = end.__gt__ else: if delta >= ZERO: raise StopIteration test = end.__lt__ while test(begin): yield begin begin += delta
In my application, interacting with a set of project management data, I needed to make changes to several days in the calendar at a time. I could have written explicit while loops, and incremented a date variable, but since I was going to be doing it several times, I extracted it to a function to improve readability and encapsulate error checking.