Python list of first day of month for given period

后端 未结 8 1586
有刺的猬
有刺的猬 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 02:44

    There is no reason to bruteforce this:

    import datetime
    from pprint import pprint
    
    dt = datetime.date.today()
    end = datetime.date(2015, 2, 1)
    dates = []
    
    while dt < end:
        if not dt.month % 12:
            dt = datetime.date(dt.year+1, 1, 1)
        else:
            dt = datetime.date(dt.year, dt.month+1, 1)
        dates.append(dt)
    
    pprint(dates)
    

    Output:

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

提交回复
热议问题