Python list of first day of month for given period

>>> 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)]

With pandas :

   dates= pd.date_range('2018-01-01','2020-01-01' , freq='1M')-pd.offsets.MonthBegin(1)

result :

`DatetimeIndex(['2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01',
               '2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01',
               '2018-09-01', '2018-10-01', '2018-11-01', '2018-12-01',
               '2019-01-01', '2019-02-01', '2019-03-01', '2019-04-01',
               '2019-05-01', '2019-06-01', '2019-07-01', '2019-08-01',
               '2019-09-01', '2019-10-01', '2019-11-01', '2019-12-01'],
              dtype='datetime64[ns]', freq='MS')

If you're only creating the list for a few years then efficiency should not be a concern. Clarity of code is the most important aspect.

dates = []
date = datetime.date.today()
while date.year < 2015:
    if date.day == 1:
        dates.append(date)
    date += datetime.timedelta(days=1)

Tags:

Python

List