Reputation: 25
I have 2 times stored in separate strings in the form of H:M
I need to get the difference between these two and be able to tell how much minutes it equals to. I was trying datetime
and timedelta
, but I'm only a beginner and I don't really understand how that works. I'm getting attribute errors everytime.
So I have a and b times, and I have to get their difference in minutes.
E.G. if a = 14:08 and b= 14:50
the difference should be 42
How do I do that in python in the simplest way possible? also, in what formats do I need to use for each step?
Upvotes: 1
Views: 319
Reputation: 106455
You can get the difference between the datetime.timedelta
objects created from the given time strings a
and b
by subtracting the former from the latter, and use the total_seconds
method to obtain the time interval in seconds, with which you can convert to minutes by dividing it by 60:
from datetime import timedelta
from operator import sub
sub(*(timedelta(**dict(zip(('hours', 'minutes'), map(int, t.split(':'))))) for t in (b, a))).total_seconds() // 60
So that given a = '29:50'
and b = '30:08'
, this returns:
18.0
Upvotes: 1
Reputation: 15357
I assume the difference is 42, not 4 (since there are 42 minutes between 14:08 and 14:50).
If the times always contains of a 5 character length string, than it's reasonably easy.
time1 = '14:08'
time2 = '15:03'
hours = int(time2[:2]) - int(time1[:2])
mins = int(time2[3:]) - int(time1[3:])
print(hours)
print(mins)
print(hours * 60 + mins)
Prints:
1
-5
55
Upvotes: 2
Reputation: 27485
You can use datetime.strptime
also the difference is 42 not 4 50-8==42
I assume that was a typo
from datetime import datetime
a,b = "14:08", "14:50"
#convert to datetime
time_a = datetime.strptime(a, "%H:%M")
time_b = datetime.strptime(b, "%H:%M")
#get timedelta from the difference of the two datetimes
delta = time_b - time_a
#get the minutes elapsed
minutes = (delta.seconds//60)%60
print(minutes)
#42
Upvotes: 2