1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| from calendar import monthrange
from datetime import date
_DELTA_ONE_DAY = datetime.timedelta(days=1)
def gen_month_list(from_dt, last_dt=None):
dt = from_dt
last_dt = last_dt or (date(dt.year+1, 1, 1) - _DELTA_ONE_DAY)
while dt < last_dt:
year, month = dt.year, dt.month
day_number = monthrange(year, month)[1]
last_date = date(year, month, day_number)
if last_date > last_dt:
last_date = last_dt
yield dt, last_date
dt = last_date + _DELTA_ONE_DAY
if __name__ == '__main__':
print ('sample')
for s, e in gen_month_list(date(2014, 5, 15)):
print (s, e)
print('check bounds: last months')
for s, e in gen_month_list(date(2014, 12, 15)):
print (s, e)
print('check bounds: year overlaps + last_dt')
for s, e in gen_month_list(date(2014, 12, 15), date(2015, 3, 15)):
print (s, e) |
Partager