Iterating through a range of dates in Python

Posted by ShawnMilo on Stack Overflow See other posts from Stack Overflow or by ShawnMilo
Published on 2009-06-29T20:16:02Z Indexed on 2010/05/06 6:18 UTC
Read the original article Hit count: 147

Filed under:
|

This is working fine, but I'm looking for any feedback on how to do it better. Right now I think it's better than nested loops, but it starts to get Perl-one-linerish when you have a generator in a list comprehension. Any suggestions are welcome.

day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n in range(day_count)) if d <= end_date]:
    print strftime("%Y-%m-%d", single_date.timetuple())

Notes: I'm not actually using this to print; that's just for demo purposes. The variables start_date and end_date are datetime.date objects, because I don't need the timestamps (they're going to be used to generate a report).

I checked the StackOverflow questions which were similar before posting this, but none were exactly the same.

Sample Output (for a start date of 2009-05-30 and an end date of 2009-06-09):

2009-05-30
2009-05-31
2009-06-01
2009-06-02
2009-06-03
2009-06-04
2009-06-05
2009-06-06
2009-06-07
2009-06-08
2009-06-09

© Stack Overflow or respective owner

Related posts about python

Related posts about datetime