I have fetched a date from database with the following variable
{{ i.operation_date }}
Look at this:
#!/usr/bin/python
import datetime
def addYears(date, years):
result = date + datetime.timedelta(366 * years)
if years > 0:
while result.year - date.year > years or date.month < result.month or date.day < result.day:
result += datetime.timedelta(-1)
elif years < 0:
while result.year - date.year < years or date.month > result.month or date.day > result.day:
result += datetime.timedelta(1)
print "input: %s output: %s" % (date, result)
return result
Example usage:
addYears(datetime.date(2012,1,1), -1)
addYears(datetime.date(2012,1,1), 0)
addYears(datetime.date(2012,1,1), 1)
addYears(datetime.date(2012,1,1), -10)
addYears(datetime.date(2012,1,1), 0)
addYears(datetime.date(2012,1,1), 10)
And output of this example:
input: 2012-01-01 output: 2011-01-01
input: 2012-01-01 output: 2012-01-01
input: 2012-01-01 output: 2013-01-01
input: 2012-01-01 output: 2002-01-01
input: 2012-01-01 output: 2012-01-01
input: 2012-01-01 output: 2022-01-01