7
>>> 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 月时,如何继续添加月份以增加年份?

4

5 回答 5

13

dateutil库对于这样的计算很有用:

>>> start_date + relativedelta(months=2)
datetime.date(1984, 1, 23)
于 2012-10-04T21:32:02.683 回答
5

使用datetime.timedeltacalendar.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)
于 2012-10-04T21:30:59.437 回答
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
于 2012-10-04T21:28:33.650 回答
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
于 2012-10-04T21:33:26.620 回答
0

您将不得不决定如何处理奇怪的情况,例如 1 月 31 日 + 1 个月 = 2 月 31 日(不存在)。但我倾向于使用 timedelta 添加到您的日期,如下所示:

import datetime as dt
dt.datetime.now() + dt.timedelta(days=30)

您可以根据当前或下个月的大小或其他一些值来选择天数,这样您就不会在下个月溢出。

于 2012-10-04T21:34:15.020 回答