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.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Both date and datetime objects have a
yearattribute, which is a number. Just add 1:If you have the current year in a variable, just add 1 directly, no need to bother with the datetime module:
If you have the date in a string, just select the 4 digits that represent the year and pass it to
int: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
dateobject with the year incremented by one:or you can use the
.replacefunction, which returns a copy with the field you specify changed:Note that this can get a little tricky when
todayis February 29th in a leap year. The absolute, fail-safe correct way to work this one is thus: