unsupported operand type(s) for -: 'str' and 'datetime.datetime'

Kenneth Ogden picture Kenneth Ogden · Oct 18, 2015 · Viewed 14.8k times · Source

I'm trying to write a Python script to count down to my next birthday. Unfortunately, I keep getting this error message stating

unsupported operand type(s) for -: 'str' and 'datetime.datetime'

Any help would be appreciated. Here's my code:

import datetime

birthday = input('Please enter your birthday(mm/dd/yyyy): ')
birthdate = datetime.datetime.strptime(birthday,'%m/%d/%Y').date()

currentDate = datetime.datetime.today()

days = birthday - currentDate
print(days)

Answer

Evan Snapp picture Evan Snapp · Oct 23, 2018

You need to use birthdate as a datetime object, and use it instead of birthday.

birthdate = datetime.datetime.strptime(birthday,'%m/%d/%Y')
currentDate = datetime.datetime.today()

days = birthdate - currentDate