获取上个月的第一天 - 月份必须在 1..12

Get first day of previous month - month must be in 1..12

我试过了,但出现错误 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 则应分别替换为 1211109

请帮忙

编辑

感谢您帮助月份,如何处理年份部分,因为它也会从 2020 变为 2019 ?请帮忙

模数运算符是您最好的选择。它正是你所需要的。您需要减去 5 而不是 4,因为数字需要流入负数才能使代码工作:

previous_month_4_start_date = today_date.replace(month=(today_date.month - 5) % 12 + 1, day=1)
# Returns: 12

可以使用modulo算术来解决这个问题,但首先你必须将month数字转换成一个有效的模12值(即 0-11) 从中减去一个。然后,您可以从该值中减去 n 个月,取模并通过再次加 1 将其转换回 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):

2020-12-01

这不处理年份变化的事实,为此你需要将当前月份与被减去的数字进行比较,如果它大于当前月份,则还从年份中减去一个:

previous_month_4_start_date = today_date.replace(year=today_date.year-1 if today_date.month <= 4 else today_date.year,
                                                 month=(today_date.month - 1 - 4) % 12 + 1, 
                                                 day=1)

输出:

2019-12-01

但是

这是很难做到的。简单的解决办法是把day设为1然后用relativedelta减去4个月:

from datetime import date
from dateutil.relativedelta import relativedelta

today_date = date.today()

previous_month_4_start_date = today_date.replace(day = 1) - relativedelta(months = 4)
print(previous_month_4_start_date)

输出:

2019-12-01
#Try this to get the previous month's first day    

from datetime import datetime,date
today_date = date.today()
if today_date.month == 1:
    previous_month_4_start_date = today_date.replace(month=(12), day=1)
else:
    previous_month_4_start_date = today_date.replace(month=(today_date.month-1), day=1)
day_name= ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday','Sunday']
print(day_name[previous_month_4_start_date.weekday()])
print(previous_month_4_start_date)