Python list of first day of month for given period

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

    You can use relativedelta from dateutil, and then create a function to use any date range:

    from datetime import date
    from dateutil.relativedelta import relativedelta
    
    def mthStList(start_date, end_date):
        stdt_list = []
        cur_date = start_date.replace(day=1) # sets date range to start of month
        while cur_date <= end_date:
            stdt_list.append(cur_date)
            cur_date += relativedelta(months=+1)
        return stdt_list
    
    mthStList(date(2012, 5, 26), date.today())
    

提交回复
热议问题