我想问你如何在Python中获得时差。假设我的开始时间是上午11:30,结束时间是下午1:00。差异将是下午1:00至11:30 = 90分钟。我是python的新手。是否存在解决这些问题的算法?然后我需要我的调度算法问题。
非常感谢您的回复。 :)
答案 0 :(得分:4)
使用内置的datetime
模块:
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
答案 1 :(得分:1)
如果由于某种原因无法使用datetime
,这是另一种解决方案。
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')