datetime.iterdate

Larry Bates lbates at swamisoft.com
Mon Jul 12 14:34:47 EDT 2004


List comprehension to the rescue:

day_range=[first+datetime.timedelta(x) for x in range((last-first).days+1))]
for day in day_range:
    do_something_with(day)

I'm not entirely sure the syntax is correct (I just
copied yours for the example) , but you get the idea.
I think it clearly defines the list of items you are
iterating over and keeps the definition close to the
loop where you do something (rather in a function
that may be defined far away in the code).

Larry Bates
Syscon, Inc.


"Robert Brewer" <fumanchu at amor.org> wrote in message
news:mailman.236.1089594533.5135.python-list at python.org...
Anyone else tired of typing date-addition logic when iterating? It would
be nice if the datetime package had something like:

def iterdates(first, last):
    for day in range((last - first).days + 1):
        yield first + datetime.timedelta(day)

...notice the inclusive boundaries (i.e. last gets returned). This
simple construct would make ugly date loops a lot cleaner:

for day in datetime.iterdates(first_date, last_date):
   do_something_with(day)



Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org





More information about the Python-list mailing list