Converting a date string to date format then do subtraction

Viewed 189

I am given two dates as strings below, and I want to subtract them to get the number 16 as my output. I tried converting them to date format first and then doing the math, but it didn't work.

from datetime import datetime

date_string = '2021-05-27'
prev_date_string = '2021-05-11'
a = datetime.strptime(date_string '%y/%m/%d')
b = datetime.strptime(prev_date_string '%y/%m/%d')
c = a - b
print (c)
2 Answers

There are two problems with the strptime calls. First, they are missing commas (,) between the two arguments. Second, the format string you use must match the format of the dates you have.

Also, note the result of subtracting two datetime objects is a timedelta object. If you just want to print out the number 16, you'll need to extract the days property of the result:

a = datetime.strptime(date_string, '%Y-%m-%d')
b = datetime.strptime(prev_date_string, '%Y-%m-%d')

c = a-b

print (c.days)

The simple answer for this problem.

from datetime import date

a = date(2021, 5, 11)
b = date(2021, 5, 27)
c = b - a
print(c.days)
Related