计算时间-1到时间-2之间的时间?
enter time-1 // eg 01:12
enter time-2 // eg 18:59
calculate: time-1 to time-2 / 12
// i.e time between 01:12 to 18:59 divided by 12
在Python中怎么做呢?我还是个初学者,所以真的不知道从哪里开始。
补充说明:我不想要一个计时器。时间1和时间2都是用户手动输入的。
提前感谢你的帮助。
4 个回答
4
这里有一个用来计时代码执行的计时器。也许你可以用它来做你想做的事情。time() 函数会返回自1970年1月1日00:00:00以来的当前时间,单位是秒和微秒。
from time import time
t0 = time()
# do stuff that takes time
print time() - t0
6
最简单直接的方式可能是这样的:
def getime(prom):
"""Prompt for input, return minutes since midnight"""
s = raw_input('Enter time-%s (hh:mm): ' % prom)
sh, sm = s.split(':')
return int(sm) + 60 * int(sh)
time1 = getime('1')
time2 = getime('2')
diff = time2 - time1
print "Difference: %d hours and %d minutes" % (diff//60, diff%60)
例如,一个典型的运行可能是:
$ python ti.py
Enter time-1 (hh:mm): 01:12
Enter time-2 (hh:mm): 18:59
Difference: 17 hours and 47 minutes
17
你需要的是内置的 datetime
模块里的 datetime
类和 timedelta
类。
from datetime import datetime
# Parse the time strings
t1 = datetime.strptime('01:12','%H:%M')
t2 = datetime.strptime('18:59','%H:%M')
# Do the math, the result is a timedelta object
delta = (t2 - t1) / 12
print(delta.seconds)