Home > Mobile >  converting a date string to date format then do subtraction
converting a date string to date format then do subtraction

Time:12-05

I am given two dates as string below, and I want to subtract to get a number 16 as my output. i tried convert them to date format first and do the math but it didn't work. Thanks in advance

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)

CodePudding user response:

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)

CodePudding user response:

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