我正在使用datetime Python模块。我希望从当前日期计算6个月的日期。有人能帮我一下吗?
我想从当前日期生成一个6个月后的日期的原因是为了生成一个回顾日期。如果用户在系统中输入数据,系统将有从输入数据之日起6个月的审查日期。
我正在使用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
根据“业务需求”解释添加月份,即日期映射到月底之后,应该映射到月底,而不是下一个月。
其他回答
还有另一个解决方案,希望有人会喜欢:
def add_months(d, months):
return d.replace(year=d.year+months//12).replace(month=(d.month+months)%12)
这个解决方案并不适用于所有情况下的第29、30、31天,所以需要更健壮的解决方案(这已经不是那么好了:)):
def add_months(d, months):
for i in range(4):
day = d.day - i
try:
return d.replace(day=day).replace(year=d.year+int(months)//12).replace(month=(d.month+int(months))%12)
except:
pass
raise Exception("should not happen")
这个怎么样?没有使用其他库(dateutil)或timedelta? 基于vartec的回答,我这样做了,我相信它是有效的:
import datetime
today = datetime.date.today()
six_months_from_today = datetime.date(today.year + (today.month + 6)/12, (today.month + 6) % 12, today.day)
我尝试使用timedelta,但因为它是计算天数的,365/2或6*356/12并不总是转换为6个月,而是182天。如。
day = datetime.date(2015, 3, 10)
print day
>>> 2015-03-10
print (day + datetime.timedelta(6*365/12))
>>> 2015-09-08
我相信我们通常会假设某一天的6个月将在6个月后的同一天登陆(即2015-03-10—> 2015-09-10,而不是2015-09-08)
我希望这对你有帮助。
我是这样解决这个问题的:
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
“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-dateutil扩展名)
from datetime import date
from dateutil.relativedelta import relativedelta
six_months = date.today() + relativedelta(months=+6)
这种方法的优势在于,它可以处理28天、30天、31天的问题。这在处理业务规则和场景(比如发票生成等)时非常有用。
$ date(2010,12,31)+relativedelta(months=+1)
datetime.date(2011, 1, 31)
$ date(2010,12,31)+relativedelta(months=+2)
datetime.date(2011, 2, 28)