Reputation: 37
I want to ask you about getting the time difference in Python. Suppose my starting time is 11:30am and ending at 1:00pm. The difference would be 1:00pm-11:30am = 90 minutes. I am new to python. Are there existing algorithms to solve these kinds of problems? I need then for my scheduling algorithm problem.
Your response would be greatly appreciated. :)
Upvotes: 2
Views: 133
Reputation:
If you cannot use datetime
for some reason here is another solution.
def minutes(time):
time, ampm = time[:-2], time[-2:]
t = time.split(":")
time = int(t[0]) * 60 + int(t[1])
if ampm == "pm":
time += 12 * 60
return time
def timeDiff(string):
start, end = string.split("-")
diff = minutes(end) - minutes(start)
if diff < 0:
diff += 24 * 60
return diff
timeDiff('11:30am-1:00pm')
Upvotes: 1
Reputation: 11534
Use the built-in datetime
module:
from datetime import datetime
start = datetime(2014, 1, 22, 11, 30)
end = datetime(2014, 1, 22, 13, 00)
minutes = (end - start).total_seconds() / 60.0
Upvotes: 4