[Tutor] iterate over daterange

Terry Carroll carroll at tjc.com
Sat Jan 7 01:08:02 CET 2006


On Fri, 6 Jan 2006, captnswing wrote:

> Hello
> I have a startdate and an enddate and I want to iterate over all days  
> in between the two
> 
> .... there doesn't seem to be a range function for dates?!?

Sounds like a good application for a generator:

#########################
def daterange(from_date, to_date, step=None):
   from datetime import timedelta
   if step is None: step = timedelta(1)
   yield_date = from_date
   while yield_date < to_date:
      yield yield_date
      yield_date = yield_date+step
#########################


To use:

#########################
import datetime
start = datetime.date(2006,1,6)
end = datetime.date(2006,1,13)
print " default: one-day step:"
for dx in daterange(start,end):
  print dx
print " two-day step:"
for dx in daterange(start, end, datetime.timedelta(2)):
  print dx
#########################

prints:


default: one-day step:
2006-01-06
2006-01-07
2006-01-08
2006-01-09
2006-01-10
2006-01-11
2006-01-12
two-day step:
2006-01-06
2006-01-08
2006-01-10
2006-01-12



More information about the Tutor mailing list