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

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

求助,我的程序是说你是哪一年出生的,然后告诉你你多大了,但我得到:

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

如果有人告诉我原因或者我把代码发给你,我将不胜感激,谢谢。

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

strftime(顾名思义)returns 一个 string,即使您可以像现在一样使用 int 将其转换为整数对于输入,您应该使用 year 属性而不是将年份作为整数获取:

 yearac = datetime.date.today().year

使用 yearac = datetime.date.today().year

因为yearac是一个字符串。试试 int(datetime.date.today().strftime("%Y"))