Python –> TypeError: unsupported operand type(s) for -: 'int' and 'str'

Question:

HELP, my program is to say what year you are born and then tell you how old you are but I get:

TypeError: unsupported operand type (s) for -: ‘int’ and ‘str’

If someone tells me why or me send the code well done I would appreciate it very much, thanks.

import  datetime
year = int(input("in what year were you born? ---> "))
yearac = datetime.date.today().strftime("%Y")
print(year)
print(yearac)
difere = year - yearac
print("You have",(difere),"years")
Asked By: Antocom LEGO

||

Answers:

strftime (as the name suggests) returns a string, and even though you can cast it to an integer using int like you’re doing with the input, you should use the year attribute instead to get the year as an integer:

 yearac = datetime.date.today().year
Answered By: DjaouadNM

use yearac = datetime.date.today().year

Answered By: RR80

It is because yearac is a string. Try int(datetime.date.today().strftime(“%Y”))

Answered By: Ruben Veldman
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.