Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (45.3k points)

I have the following code to do this, but how can I 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.

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 start_date and end_date variables are datetime.date objects because I don't need the timestamps. (They're going to be used to generate a report).

Sample Output

For a start date of 2009-05-30 and the 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

1 Answer

0 votes
by (16.8k points)

The best way to do this is by using generator function to hide/abstract the iteration over the ranges of dates:

from datetime import timedelta, date

def daterange(start_date, end_date):

    for n in range(int ((end_date - start_date).days)):

        yield start_date + timedelta(n)

start_date = date(2013, 1, 1)

end_date = date(2015, 6, 2)

for single_date in daterange(start_date, end_date):

    print single_date.strftime("%Y-%m-%d")

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...