0

My current code:

import datetime
from time import strptime
leapyear = 0

isValid = False
while not isValid:
     in_date = input(" Please in put a year in the format dd/mm/yyyy ")
     try:
         d = strptime(in_date, '%d/%m/%Y')
         isValid=True
     except:
         print ("This is not in the right format")

diff = d -datetime.date.today()
print(in_date)
print(d)
print(diff)

I cannot subtract the two dates, the input date and today's date from each other. It throws a TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'datetime.date' exception.

Any ideas why?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user3077551
  • 69
  • 2
  • 9

2 Answers2

0

The datetime module objects only support subtraction with other objects from the same library. The time module struct_time tuple is not one of those.

Use the datetime.datetime.strptime() class method to parse the date instead:

 d = datetime.datetime.strptime(in_date, '%d/%m/%Y')

then use the datetime.date() method to extract just a date object from the result:

diff = d.date() - datetime.date.today()

The result is a datetime.timedelta instance.

Don't catch all exceptions; catch just those thrown by strptime() when passed a string that doesn't match the expected format, ValueError:

while True:
     in_date = input(" Please in put a year in the format dd/mm/yyyy ")
     try:
         d = datetime.datetime.strptime(in_date, '%d/%m/%Y').date()
         break
     except ValueError:
         print ("This is not in the right format")

I used break here to end the while loop rather than use a flag variable.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0
import datetime
from datetime import strptime
currentdate=datetime.date.today()
date_str = input("enter date in format dd/mm/yyy") #inputed date is in string need to conver ot into date 
#format_str = '%d/%m/%Y' # The format
datetime_obj = datetime.datetime.strptime(date_str, '%d/%m/%Y') # convert inputed date into date 
diff= datetime_obj.date() - currentdate # take .date because we only need date not time 

print("Current date ==",currentdate)
print("entered date ==",datetime_obj.date()) 
print("remaining Days left  ===",diff)