简体   繁体   中英

Find difference between two time strings in Python

I have two times in the string format HHMM and I want to find the difference in minutes.

I've tried the below but I'm getting the following error:

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

import datetime  

a = "0628"
b = "0728"

aSep = a[:2] + ':' + a[2:]
bSep = b[:2] + ':' + b[2:]

timeA = datetime.datetime.strptime(aSep, '%H:%M').time()
timeB = datetime.datetime.strptime(bSep, '%H:%M').time()

diff = timeB -timeA
print diff
import datetime  

a = "0628"
b = "0728"

timeA  = datetime.datetime.strptime(a, "%H%M")
timeB  = datetime.datetime.strptime(b, "%H%M")

print((timeB-timeA).total_seconds())
print(((timeB-timeA).total_seconds()/60.0))

Output:

3600.0
60.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM