Search code examples
pythonpandaslistdatetimerelativedelta

Create a list of sequent year month in Python


I try to create a list of year-month from 2020-06 (last month from today) to 2021-05 using the following code:

from datetime import datetime
from dateutil.relativedelta import relativedelta
need_months = list(range(-1, 12))
print([(datetime.today()+ relativedelta(months=i if i < 0 else i - 1)).strftime('%Y-%m') for i in need_months])

Out:

['2020-06', '2020-06', '2020-07', '2020-08', '2020-09', '2020-10', '2020-11', '2020-12', '2021-01', '2021-02', '2021-03', '2021-04', '2021-05']

But as you may noticed, there are two 2020-06 in the list.

How could I do it correctly?

The expected result:

['2020-06', '2020-07', '2020-08', '2020-09', '2020-10', '2020-11', '2020-12', '2021-01', '2021-02', '2021-03', '2021-04', '2021-05']

Solution

  • Here is possible use period_range with convert today to month period by Timestamp.to_period, for previous month subtract 1 and add 12 periods parameter:

    now = pd.Timestamp.now().to_period('m')
    L = pd.period_range(now-1, freq='M', periods=12).strftime('%Y-%m').tolist()
    print (L)
    ['2020-06', '2020-07', '2020-08', '2020-09', '2020-10', '2020-11', 
     '2020-12', '2021-01', '2021-02', '2021-03', '2021-04', '2021-05']