Python list of first day of month for given period

后端 未结 8 1580
有刺的猬
有刺的猬 2021-02-09 02:20

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         


        
8条回答
  •  别那么骄傲
    2021-02-09 03:04

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

提交回复
热议问题