在 Python 中创建后续年月的列表

Create a list of sequent year month in Python

我尝试使用以下代码创建从 2020-06(从今天开始的上个月)到 2021-05year-month 列表:

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])

输出:

['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']

但是您可能已经注意到,列表中有两个 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']

改变

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

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])

输出:-

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

这里可以使用 period_range with convert today to month period by Timestamp.to_period,对于上个月减去 1 并添加 12 个周期参数:

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']

relativedata 中删除 if-else 按预期工作:

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])

输出:

['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']