Python list of first day of month for given period

后端 未结 8 1599
有刺的猬
有刺的猬 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:03

    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.

    0 讨论(0)
  • 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)]
    
    0 讨论(0)
提交回复
热议问题