Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Print next year from current year in Python

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.

like image 969
Alchemist777 Avatar asked Jun 26 '12 11:06

Alchemist777


People also ask

How do you get the current year in Python?

To get the current year in Python, first we need to import the date class from the datetime module and call a today(). year on it. The year property returns the current year in four-digit(2021) string format according to the user's local time.

How do I get the current year and month in Python?

From the DateTime module, import date class. Create an object of the date class. Call the today( ) function of date class to fetch todays date. By using the object created, we can print the year, month, day(attribute of date class) of today.


1 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) 
like image 196
Martijn Pieters Avatar answered Oct 08 '22 09:10

Martijn Pieters