Iterate thru dates in Python

Posted on Friday, February 19th, 2010 under ,

Few days ago I was working on some python scripts that needed to iterate back and forth through calendar dates. Working with dates in python is pretty easy, due to its datetime package.

Basically is like this:

#!/usr/bin/env python
 
import datetime
 
start_date = datetime.date( year = 2010, month = 2, day = 1 )
end_date = datetime.date( year = 2010, month = 1, day = 1 )
 
list = []
 
if start_date <= end_date:
    for n in range( ( end_date - start_date ).days + 1 ):
        list.append( start_date + datetime.timedelta( n ) )
else:
    for n in range( ( start_date - end_date ).days + 1 ):
        list.append( start_date - datetime.timedelta( n ) )
 
for d in list:
    print d

This works, but is somewhat lame and not quite reusable. The most “python-ish” way to do it is to create a generator function that will yield the current date and can be used in a for loop. So I did it:

#!/usr/bin/env python
import datetime
 
def daterange( start_date, end_date ):
    if start_date <= end_date:
        for n in range( ( end_date - start_date ).days + 1 ):
            yield start_date + datetime.timedelta( n )
    else:
        for n in range( ( start_date - end_date ).days + 1 ):
            yield start_date - datetime.timedelta( n )
 
start = datetime.date( year = 2010, month = 2, day = 1 )
end = datetime.date( year = 2010, month = 1, day = 1 )
 
for date in daterange( start, end ):
    print date

Much more elegant :)

Related posts

One Response to “Iterate thru dates in Python”

  1. Jason Wiener

    Nice. Thanks for sharing.

Leave a Reply