How to include end date in pandas date_range method?

前端 未结 7 1713
[愿得一人]
[愿得一人] 2021-01-02 02:42

From pd.date_range(\'2016-01\', \'2016-05\', freq=\'M\', ).strftime(\'%Y-%m\'), the last month is 2016-04, but I was expecting it to be 2016

7条回答
  •  情话喂你
    2021-01-02 03:04

    You can use .union to add the next logical value after initializing the date_range. It should work as written for any frequency:

    d = pd.date_range('2016-01', '2016-05', freq='M')
    d = d.union([d[-1] + 1]).strftime('%Y-%m')
    

    Alternatively, you can use period_range instead of date_range. Depending on what you intend to do, this might not be the right thing to use, but it satisfies your question:

    pd.period_range('2016-01', '2016-05', freq='M').strftime('%Y-%m')
    

    In either case, the resulting output is as expected:

    ['2016-01' '2016-02' '2016-03' '2016-04' '2016-05']
    

提交回复
热议问题