2

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']
ah bon
  • 9,293
  • 12
  • 65
  • 148

3 Answers3

2

Change

need_months = list(range(-1, 12))

to

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

Output:-

'2020-06', '2020-07', '2020-08', '2020-09', '2020-10', '2020-11', '2020-12', '2021-01', '2021-02', '2021-03', '2021-04', '2021-05']
Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
2

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']
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 2
    I think there is error: `strftime('%Y-%M')`, `M` should be `m`? – ah bon Jul 08 '20 at 05:48
  • In fact, I'm trying to avoid to use a definitive date value `2021-05`, that's why I create a list. In stead, I hope the date list ends in the next `12` months starting from `2020-06`. – ah bon Jul 08 '20 at 05:54
  • 1
    @ahbon - Just it is simplier if use 12 periods parameter, edited answer. – jezrael Jul 08 '20 at 05:58
1

Getting rid of if-else in relativedata works as expected:

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

Output:

['2020-05', '2020-06', '2020-07', '2020-08', '2020-09', '2020-10', '2020-11', '2020-12', '2021-01', '2021-02', '2021-03', '2021-04', '2021-05']
Chris
  • 29,127
  • 3
  • 28
  • 51