python年份增加,在当前日期添加一年PYTHON

I have fetched a date from database with the following variable

{{ i.operation_date }}

with which I got a value like

April 1, 2013

I need to add one year to the above, so that I can get

April 1, 2014

Please suggest, how can I do this?

解决方案

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年份增加)