我需要增加一个datetime值的月份

next_month = datetime.datetime(mydate.year, mydate.month+1, 1)

当月份为12时,它变成13,并引发错误“month必须在1..12”。(我预计时间会增加)

我想使用timedelta,但它不带month参数。 有一个relativedelta python包,但我不想只为此安装它。 还有一个使用strtotime的解决方案。

time = strtotime(str(mydate));
next_month = date("Y-m-d", strtotime("+1 month", time));

我不想从datetime转换为str再转换为time,再转换为datetime;因此,它仍然是一个图书馆

有人有像使用timedelta一样好的简单的解决方案吗?


当前回答

这个怎么样?(不需要任何额外的库)

from datetime import date, timedelta
from calendar import monthrange

today = date.today()
month_later = date(today.year, today.month, monthrange(today.year, today.month)[1]) + timedelta(1)

其他回答

不使用日历的解决方案:

def add_month_year(date, years=0, months=0):
    year, month = date.year + years, date.month + months + 1
    dyear, month = divmod(month - 1, 12)
    rdate = datetime.date(year + dyear, month + 1, 1) - datetime.timedelta(1)
    return rdate.replace(day = min(rdate.day, date.day))

使用time对象的示例:

start_time = time.gmtime(time.time())    # start now

#increment one month
start_time = time.gmtime(time.mktime([start_time.tm_year, start_time.tm_mon+1, start_time.tm_mday, start_time.tm_hour, start_time.tm_min, start_time.tm_sec, 0, 0, 0]))

好的,通过一些调整和使用timedelta,我们开始:

from datetime import datetime, timedelta


def inc_date(origin_date):
    day = origin_date.day
    month = origin_date.month
    year = origin_date.year
    if origin_date.month == 12:
        delta = datetime(year + 1, 1, day) - origin_date
    else:
        delta = datetime(year, month + 1, day) - origin_date
    return origin_date + delta

final_date = inc_date(datetime.today())
print final_date.date()

与Dave Webb的解决方案的理想相似,但没有所有棘手的模运算:

import datetime, calendar

def increment_month(date):
    # Go to first of this month, and add 32 days to get to the next month
    next_month = date.replace(day=1) + datetime.timedelta(32)
    # Get the day of month that corresponds
    day = min(date.day, calendar.monthrange(next_month.year, next_month.month)[1])
    return next_month.replace(day=day)

我的解决方案非常简单,不需要任何额外的模块:

def addmonth(date):
    if date.day < 20:
        date2 = date+timedelta(32)
    else :
        date2 = date+timedelta(25)
    date2.replace(date2.year, date2.month, day)
    return date2