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).