For and Dates
Fredrik Lundh
fredrik at pythonware.com
Thu Jun 13 13:30:01 EDT 2002
"Marcus Vinicius Laranjeira" wrote:
> 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 !?
if you can live with a while-loop, here's one (rather
simple-minded) way to do it:
import time
now = time.mktime((2002, 6, 1) + (0, 0, 0, 0, 0, 0))
end = time.mktime((2002, 7, 31) + (0, 0, 0, 0, 0, 0))
while now <= end:
y, m, d = time.localtime(now)[:3]
# do something with y, m, d
print y, m, d
now = now + 86400
here's another one:
import calendar
def tomorrow((year, month, day)):
weekday, mdays = calendar.monthrange(year, month)
day = day + 1
if day > mdays:
day = 1
month = month + 1
if month > 12:
month = 1
year = year + 1
return year, month, day
now = 2002, 6, 1
while now <= (2002, 7, 31):
y, m, d = now
# do something with y, m, d
print y, m, d
now = tomorrow(now)
if you really need to use a for-in loop, and you're using
Python 2.2, it's straightforward to convert either of these
to use a generator instead:
from __future__ import generators
...
def dayrange(now, end):
while now <= end:
yield now
now = tomorrow(now)
for y, m, d in dayrange((2002, 6, 1), (2002, 7, 31)):
# do something with y, m, d
print y, m, d
</F>
More information about the Python-list
mailing list