For and Dates

Mark McEahern marklists at mceahern.com
Thu Jun 13 12:11:52 EDT 2002


> I need to do a loop that goes from 2002-6-1 to 2002-7-31, but I don't know
> how to do that...
>
> Is there a way to do such range using for !?
>
> Do you have any suggestions !?

Short answer:

	Use mx.DateTime + generators

Demo:

from __future__ import generators

import mx.DateTime

def date_span_gen(d1, d2):
    """Return an iterator for the dates between d1 and d2."""
    if d2 <= d1:
        raise RuntimeError("d2 (%s) must be later than d1 (%s)." % (d2, d1))
    diff = d2 - d1
    for d in range(diff.days):
        yield (d1 + mx.DateTime.RelativeDateTime(days=d))

num_days = 30
d1 = mx.DateTime.now()
d2 = d1 + mx.DateTime.RelativeDateTime(days=num_days)

for d in date_span_gen(d1, d2):
    print d

-






More information about the Python-list mailing list