简体   繁体   中英

How to get a time interval between two strings?

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.

EG . 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?

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
  • hours will be the integer value of the left two digits [:1] subtraction of the second and first time
  • minutes will be the integer value of the right two digits [3:] subtraction of the second and first time
  • This prints 55 ... with your values it prints out 42 (the above example is to show it also works when moving over a whole hour.

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

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

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