我正在使用datetime Python模块。我希望从当前日期计算6个月的日期。有人能帮我一下吗?
我想从当前日期生成一个6个月后的日期的原因是为了生成一个回顾日期。如果用户在系统中输入数据,系统将有从输入数据之日起6个月的审查日期。
我正在使用datetime Python模块。我希望从当前日期计算6个月的日期。有人能帮我一下吗?
我想从当前日期生成一个6个月后的日期的原因是为了生成一个回顾日期。如果用户在系统中输入数据,系统将有从输入数据之日起6个月的审查日期。
当前回答
假设你的datetime变量叫做date:
date=datetime.datetime(year=date.year+int((date.month+6)/12),
month=(date.month+6)%13 + (1 if (date.month +
months>12) else 0), day=date.day)
其他回答
“Python -dateutil”(外部扩展)是一个很好的解决方案,但你可以使用内置的Python模块(datetime和datetime)来实现它。
我做了一个简短的代码,来解决它(处理年,月和日)
(运行:Python 3.8.2)
from datetime import datetime
from calendar import monthrange
# Time to increase (in months)
inc = 12
# Returns mod of the division for 12 (months)
month = ((datetime.now().month + inc) % 12) or 1
# Increase the division by 12 (months), if necessary (+ 12 months increase)
year = datetime.now().year + int((month + inc) / 12)
# (IF YOU DON'T NEED DAYS,CAN REMOVE THE BELOW CODE)
# Returns the same day in new month, or the maximum day of new month
day = min(datetime.now().day,monthrange(year, month)[1])
print("Year: {}, Month: {}, Day: {}".format(year, month, day))
使用python datetime模块为datetime.today()添加6个月的时间增量。
http://docs.python.org/library/datetime.html
你当然要解决Johannes weß提出的问题——你说的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
根据“业务需求”解释添加月份,即日期映射到月底之后,应该映射到月底,而不是下一个月。
这里有一个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)
Python的datetime没有直接的方法来做到这一点。
在python-dateutil中查看relativedelta类型。它允许您指定以月为单位的时间增量。