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

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


当前回答

我是这样解决这个问题的:

import calendar
from datetime import datetime
moths2add = 6
now = datetime.now()
current_year = now.year
current_month = now.month
#count days in months you want to add using calendar module
days = sum(
  [calendar.monthrange(current_year, elem)[1] for elem in range(current_month, current_month + moths)]
    )
print now + days

其他回答

你说6个月是什么意思?

2009-02-13 + 6个月== 2009-08-13?还是2009-02-13 + 6*30天?

import mx.DateTime as dt

#6 Months
dt.now()+dt.RelativeDateTime(months=6)
#result is '2009-08-13 16:28:00.84'

#6*30 days
dt.now()+dt.RelativeDateTime(days=30*6)
#result is '2009-08-12 16:30:03.35'

更多关于mx的信息。DateTime

另一种解决方案:计算下个月的天数总和,并将结果添加到当前日期。

import calendar
import datetime

def date_from_now(months):
    today = datetime.datetime.today()

    month = today.month
    year = today.year
    sum_days = 0

    for i in range(int(months)):
        month += 1

        if month == 13:
            month = 1
            year += 1

        sum_days += calendar.monthrange(year, month)[1]

    return datetime.date.today() + datetime.timedelta(sum_days)

print(date_from_now(12)) # if to day is 2017-01-01, output: 2019-01-01 
    def addDay(date, number):
        for i in range(number)
            #try to add a day
            try:
                date = date.replace(day = date.day + 1)
            #in case it's impossible ex:january 32nd add a month and restart at day 1
            except:
                #add month part
                try:
                    date = date.replace(month = date.month +1, day = 1)
                except:
                    date = date.replace(year = date.year +1, month = 1, day = 1)

写给还在读这篇文章的人。我认为这段代码更加清晰,特别是与使用模(%)的代码相比。

很抱歉有语法错误,英语不是我的主要语言

使用python datetime模块为datetime.today()添加6个月的时间增量。

http://docs.python.org/library/datetime.html

你当然要解决Johannes weß提出的问题——你说的6个月是什么意思?

这里有一个dateutil的例子。relativedelta,我发现它对于迭代过去一年很有用,每次跳过一个月到现在的日期:

>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> today = datetime.datetime.today()
>>> month_count = 0
>>> while month_count < 12:
...  day = today - relativedelta(months=month_count)
...  print day
...  month_count += 1
... 
2010-07-07 10:51:45.187968
2010-06-07 10:51:45.187968
2010-05-07 10:51:45.187968
2010-04-07 10:51:45.187968
2010-03-07 10:51:45.187968
2010-02-07 10:51:45.187968
2010-01-07 10:51:45.187968
2009-12-07 10:51:45.187968
2009-11-07 10:51:45.187968
2009-10-07 10:51:45.187968
2009-09-07 10:51:45.187968
2009-08-07 10:51:45.187968

和其他答案一样,你必须弄清楚你说的“6个月后”到底是什么意思。如果你的意思是“六年后某个月的今天”,那么这个是:

datetime.datetime.now() + relativedelta(months=6)