Python list of first day of month for given period

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

    Try pandas.date_range() with the 'MS' (Month Start) frequency alias:

    import pandas as pd
    
    start = '2020-01-01'
    end = '2020-12-01'
    
    dates = pd.date_range(start, end, freq='MS')
    
    print(dates)
    

    Result:

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

    A list of all frequency aliases can be found here.

提交回复
热议问题