如何从python中的YYYYMM字符串日期中减去月份?

问题描述 投票:0回答:1

我有日期为(YYYYMM)的字符串,即:201909。

在Python中,我如何简单地减去一个月?

从日期时间导入日期时间

Month = '201905'
Month = datetime.strptime(Month, '%Y%m').date()
Month1 = str(Month -1)
Month2 = str(Month -2)
Month3 = str(Month -3)
Month6 = str(Month -6)
Month12 = str(Month - 100)

这不起作用,但是我希望能够将'Month'变量设置为类似'201905'的字符串,并从那里计算各种YYYYMM字符串。

python date-formatting
1个回答
0
投票
Month = '201912' 
month = 12 if (int(Month[-2:]) -1 ) % 12 == 0 else (int(Month[-2:]) -1 ) % 12

print (month)
© www.soinside.com 2019 - 2024. All rights reserved.