Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterator for dates in python

I have a begin_date datetime.date(2012, 9, 1) and an end_date datetime.date(2012, 9, 30)

I would like get a iterator or a list which includes dates 2012/9/1 to 2012/9/30. Is any way other then a loop do make that iterator or list

like image 909
waitingkuo Avatar asked Dec 07 '22 10:12

waitingkuo


1 Answers

Use a generator:

from datetime import date, timedelta

def dategenerator(start, end):
    current = start
    while current <= end:
        yield current
        current += timedelta(days=1)

Demo:

>>> for dt in dategenerator(date(2012, 9, 1), date(2012, 9, 30)):
...     print dt
... 
2012-09-01
2012-09-02
2012-09-03
2012-09-04
2012-09-05
2012-09-06
2012-09-07
2012-09-08
2012-09-09
2012-09-10
2012-09-11
2012-09-12
2012-09-13
2012-09-14
2012-09-15
2012-09-16
2012-09-17
2012-09-18
2012-09-19
2012-09-20
2012-09-21
2012-09-22
2012-09-23
2012-09-24
2012-09-25
2012-09-26
2012-09-27
2012-09-28
2012-09-29
2012-09-30
like image 51
Martijn Pieters Avatar answered Dec 20 '22 14:12

Martijn Pieters