I am trying find an efficient way of creating a list of dates only including the first day of the month for a given period. Something like this but better:
impor
This is the same as @Andrew's answer, but much faster:
dates = []
date = datetime.date.today()
while date.year < 2015:
if date.day == 1:
dates.append(date)
# I added the following line:
date += datetime.timedelta(days=27)
date += datetime.timedelta(days=1)
Using force, but not being brutal.
>>> startyear = 2014
>>> startmonth = 4
>>> endyear = 2015
>>> endmonth = 2
>>> [datetime.date(m/12, m%12+1, 1) for m in xrange(startyear*12+startmonth-1, endyear*12+endmonth)]
[datetime.date(2014, 4, 1), datetime.date(2014, 5, 1), datetime.date(2014, 6, 1), datetime.date(2014, 7, 1), datetime.date(2014, 8, 1), datetime.date(2014, 9, 1), datetime.date(2014, 10, 1), datetime.date(2014, 11, 1), datetime.date(2014, 12, 1), datetime.date(2015, 1, 1), datetime.date(2015, 2, 1)]
For Python 3, you'll need to use range
instead of xrange
, and //
(floor division) instead of /
(which does float division in Python 3):
[datetime.date(m//12, m%12+1, 1) for m in range(startyear*12+startmonth-1, endyear*12+endmonth)]