在当前日期添加一年PYTHON [英] Add one year in current date PYTHON
本文介绍了在当前日期添加一年PYTHON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从数据库中获取了日期,并使用以下变量
I have fetched a date from database with the following variable
{{ i.operation_date }}
价值如
April 1, 2013
我需要在上面添加一年,以便我可以获得
I need to add one year to the above, so that I can get
April 1, 2014
请建议,我该怎么做?
推荐答案
AGSM的答案显示了一种方便的方法来解决此问题 python-dateutil
包。但是如果您不想安装该包,该怎么办?你可以像这样解决这个问题:
AGSM's answer shows a convenient way of solving this problem using the python-dateutil
package. But what if you don't want to install that package? You could solve the problem in vanilla Python like this:
from datetime import date
def add_years(d, years):
"""Return a date that's `years` years after the date (or datetime)
object `d`. Return the same calendar date (month and day) in the
destination year, if it exists, otherwise use the following day
(thus changing February 29 to March 1).
"""
try:
return d.replace(year = d.year + years)
except ValueError:
return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1))
这篇关于在当前日期添加一年PYTHON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文