>>> start_date = date(1983, 11, 23)
>>> start_date.replace(month=start_date.month+1)
datetime.date(1983, 12, 23)
这一直有效,直到月<=11
,我一直
>>> start_date = date(1983, 12, 23)
>>> start_date.replace(month=start_date.month+1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: month must be in 1..12
如何将新月添加到12月时,如何增加月份的增量?
答案 0 :(得分:9)
dateutil库对于这样的计算非常有用:
>>> start_date + relativedelta(months=2)
datetime.date(1984, 1, 23)
答案 1 :(得分:4)
try:
start_date.replace(month=start_date.month+1)
except ValueError:
if start_date.month == 12:
start_date.replace(month=1)
start_date.replace(year=start_date.year+1)
else:
raise
答案 2 :(得分:4)
使用datetime.timedelta
和calendar.monthrange
:
>>> from datetime import date, timedelta
>>> import calendar
>>> start_date = date(1983, 12, 23)
>>> days_in_month = calendar.monthrange(start_date.year, start_date.month)[1]
>>> start_date + timedelta(days=days_in_month)
datetime.date(1984, 1, 23)
答案 3 :(得分:1)
你将不得不决定如何处理奇怪的案例,例如1月31日+ 1月= 2月31日(不存在)。但我倾向于使用timedelta添加到你的日期,如:
import datetime as dt
dt.datetime.now() + dt.timedelta(days=30)
您可以根据当前或下个月的大小或某些其他值来选择日期,以便下个月不会溢出。
答案 4 :(得分:0)
如果您想要针对此问题提供更通用的解决方案,例如将日期,月份和年份混合到一个日期:
import time, datetime, calendar
def upcount(dt, years=0, months=0, **kwargs):
if months:
total_months = dt.month + months
month_years, months = divmod(total_months, 12)
if months == 0:
month_years -= 1
months = 12
years += month_years
else:
months = dt.month
years = dt.year + years
try:
dt = dt.replace(year=years, month=months)
except ValueError:
# 31st march -> 31st april gives this error
max_day = calendar.monthrange(years, months)[1]
dt = dt.replace(year=years, month=months, day=max_day)
if kwargs:
dt += datetime.timedelta(**kwargs)
return dt