我需要增加日期时间值的月份
next_month = datetime.datetime(mydate.year, mydate.month+1, 1)
当月份为 12 时,它变为 13,并引发错误“月份必须在 1..12”。 (我预计年份会增加)
我想使用 timedelta,但它不需要月份参数。有relativedelta python 包,但我不想只为此安装它。还有一个使用strtotime的解决方案。
time = strtotime(str(mydate)); next_month = date("Y-m-d", strtotime("+1 month", time));
我不想从 datetime 转换为 str,然后转换为时间,然后再转换为 datetime;因此,它仍然是一个库
有没有人有像使用 timedelta 一样好的、简单的解决方案?
要增加月份datetime客体与汉
datetime
import datetime def add_months(mydate, months): # Calculate the new year and month new_month = mydate.month + months new_year = mydate.year + (new_month - new_month = mydate.month + months new_year = mydate.year + (new_month new_month = mydate.month + months new_year = mydate.year + ( new_month = mydate.month + months new_year = new_month = mydate.month + months new_month = 1) // 12 new_month = (new_month - new_month = ( new_month = 1) % 12 + 1 # Return the new date (we assume you want the first day of the next month) return datetime.datetime(new_year, new_month, 1) # Example usage: mydate = datetime.datetime( mydate = datetime.da mydate = datet mydate = da mydat m 2023, 12, 15) next_month = add_months(mydate, next_month = add_months(mydate, next_month = add_months(my next_month = 1) print(next_month) # Output: 2024-01-01 00:00:00 ``
:
mydate.month + months
(new_month - 1) // 12
% 12然后使用模数设置新月份
% 12
返回更新日期
这样,你就可以