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))
If you want the other possibility (changing February 29 to February 28) then the last line should be changed to:
return d + (date(d.year + years, 3, 1) - date(d.year, 3, 1))
You can use Python-dateutil's relativedelta
to increment a datetime
object while remaining sensitive to things like leap years and month lengths. Python-dateutil comes packaged with matplotlib if you already have that. You can do the following:
from dateutil.relativedelta import relativedelta new_date = old_date + relativedelta(years=1)
(This answer was given by @Max to a similar question).
But if your date is a string (i.e. not already a datetime
object) you can convert it using datetime:
from datetime import datetime from dateutil.relativedelta import relativedelta your_date_string = "April 1, 2012" format_string = "%B %d, %Y" datetime_object = datetime.strptime(your_date_string, format_string).date() new_date = datetime_object + relativedelta(years=1) new_date_string = datetime.strftime(new_date, format_string).replace(' 0', ' ')
new_date_string
will contain "April 1, 2013".
NB: Unfortunately, datetime
only outputs day values as "decimal numbers" - i.e. with leading zeros if they're single digit numbers. The .replace()
at the end is a workaround to deal with this issue copied from @Alex Martelli (see this question for his and other approaches to this problem).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With