How to Print next year from current year in Python

Question:

How can I print the next year if the current year is given in python using the simplest code, possibly in one line using datetime module.

Asked By: Alchemist777

||

Answers:

Both date and datetime objects have a year attribute, which is a number. Just add 1:

>>> from datetime import date
>>> print date.today().year + 1
2013

If you have the current year in a variable, just add 1 directly, no need to bother with the datetime module:

>>> year = 2012
>>> print year + 1
2013

If you have the date in a string, just select the 4 digits that represent the year and pass it to int:

>>> date = '2012-06-26'
>>> print int(date[:4]) + 1
2013

Year arithmetic is exceedingly simple, make it an integer and just add 1. It doesn’t get much simpler than that.

If, however, you are working with a whole date, and you need the same date but one year later, use the components to create a new date object with the year incremented by one:

>>> today = date.today()
>>> print date(today.year + 1, today.month, today.day)
2013-06-26

or you can use the .replace function, which returns a copy with the field you specify changed:

>>> print today.replace(year=today.year + 1)
2013-06-26

Note that this can get a little tricky when today is February 29th in a leap year. The absolute, fail-safe correct way to work this one is thus:

def nextyear(dt):
   try:
       return dt.replace(year=dt.year+1)
   except ValueError:
       # February 29th in a leap year
       # Add 365 days instead to arrive at March 1st
       return dt + timedelta(days=365)
Answered By: Martijn Pieters

here is another simple way…

import datetime

x = datetime.datetime.now()

print(x.year+1)
Answered By: TRoberts
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.