Gray Ridley
Gray Ridley

Reputation: 63

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

Upvotes: 1

Views: 1651

Answers (1)

Rakesh
Rakesh

Reputation: 82755

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

Upvotes: 2

Related Questions