我正在使用datetime Python模块。我希望从当前日期计算6个月的日期。有人能帮我一下吗?

我想从当前日期生成一个6个月后的日期的原因是为了生成一个回顾日期。如果用户在系统中输入数据,系统将有从输入数据之日起6个月的审查日期。


当前回答

我对Tony Diep的答案的修改,可能稍微更优雅(当然,Python 2,匹配问题和原始答案的日期,对于Python 3,必要时修改,至少包括/ to //):

def add_months(date, months):
    month = date.month + months - 1
    year = date.year + (month / 12)
    month = (month % 12) + 1
    day = date.day
    while (day > 0):
        try:
            new_date = date.replace(year=year, month=month, day=day)
            break
        except:
            day = day - 1    
    return new_date

根据“业务需求”解释添加月份,即日期映射到月底之后,应该映射到月底,而不是下一个月。

其他回答

嗯,这取决于你说的6个月后的日期。

使用自然月份: Inc = 6 年=年+(月+ inc - 1) // 12 月份=(月份+ inc - 1) % 12 + 1 用银行家的定义,6*30: 日期+=日期时间。Timedelta (6 * 30)

修改了AddMonths()在Zope中使用和处理无效的天数:

def AddMonths(d,x):
    days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    newmonth = ((( d.month() - 1) + x ) % 12 ) + 1
    newyear  = d.year() + ((( d.month() - 1) + x ) // 12 ) 
    if d.day() > days_of_month[newmonth-1]:
      newday = days_of_month[newmonth-1]
    else:
      newday = d.day() 
    return DateTime( newyear, newmonth, newday)

下面是一个示例,它允许用户决定如何返回一个日期,其中一天大于一个月中的天数。

def add_months(date, months, endOfMonthBehaviour='RoundUp'):
    assert endOfMonthBehaviour in ['RoundDown', 'RoundIn', 'RoundOut', 'RoundUp'], \
        'Unknown end of month behaviour'
    year = date.year + (date.month + months - 1) / 12
    month = (date.month + months - 1) % 12 + 1
    day = date.day
    last = monthrange(year, month)[1]
    if day > last:
        if endOfMonthBehaviour == 'RoundDown' or \
            endOfMonthBehaviour == 'RoundOut' and months < 0 or \
            endOfMonthBehaviour == 'RoundIn' and months > 0:
            day = last
        elif endOfMonthBehaviour == 'RoundUp' or \
            endOfMonthBehaviour == 'RoundOut' and months > 0 or \
            endOfMonthBehaviour == 'RoundIn' and months < 0:
            # we don't need to worry about incrementing the year
            # because there will never be a day in December > 31
            month += 1
            day = 1
    return datetime.date(year, month, day)


>>> from calendar import monthrange
>>> import datetime
>>> add_months(datetime.datetime(2016, 1, 31), 1)
datetime.date(2016, 3, 1)
>>> add_months(datetime.datetime(2016, 1, 31), -2)
datetime.date(2015, 12, 1)
>>> add_months(datetime.datetime(2016, 1, 31), -2, 'RoundDown')
datetime.date(2015, 11, 30)

我们可能应该使用dateutil。relativedelta

然而,出于学术兴趣,我只想补充一点,在我发现它之前,我打算用这个:

亿: 今天代表。年度+ (K .今日month + 6) / 12 / (K . today . 12 month + 5%) + 1, K .今日day)。 except: 今天代表。年+ (K.today.month+6)//12 (K.today.month+6)%12+1, 1) -时间轴(天= 1)

它看起来很简单,但仍然可以捕捉到所有的问题,如29、30、31

它也适用于- 6 MTHS通过执行-timedelta

别被k弄糊涂了,今天它只是我程序中的一个变量

我插话晚了,但是

查看肯雷茨玛雅模块,

https://github.com/kennethreitz/maya

像这样的方法可能会对你有帮助,只需将小时=1改为天=1或年=1

>>> from maya import MayaInterval

# Create an event that is one hour long, starting now.
>>> event_start = maya.now()
>>> event_end = event_start.add(hours=1)

>>> event = MayaInterval(start=event_start, end=event_end)