我尝试过此操作,但出现错误month must be in 1..12
:
today_date = date.today()
# ERROR - month value becomes -1 here instead of 12
previous_month_4_start_date = today_date.replace(month=today_date.month - 4, day=1)
我可以编写一些样板代码来解决此问题,但是正在寻找一种有效的方法,如果month
是-1
或-2
或-3
或-4
,则应将其替换为12
或[C0 ]或11
或10
。
请帮助
9
可以使用previous_month_4_start_date = today_date.replace(month=(today_date.month - 4) % 12 + 1, day=1)
# Returns: 12
算术解决此问题,但首先您必须通过从中减去1,将modulo
数字转换为有效模12(即month
)的值。然后,您可以从该值中减去0-11
个月,取模数,然后通过再次加1将其转换回n
数字:
month
输出(从today_date = date.today() previous_month_4_start_date = today_date.replace(month=(today_date.month - 1 - 4) % 12 + 1, day=1) print(previous_month_4_start_date)
开始):
2020-04-14