python 计算时间 1 到时间 2 之间的时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1965201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate time between time-1 to time-2?
提问by eozzy
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
How can it be done in Python. I'm a beginner so I really have no clue where to start.
如何在 Python 中完成。我是初学者,所以我真的不知道从哪里开始。
Edited to add: I don't want a timer. Both time-1 and time-2 are entered by the user manually.
编辑添加:我不想要一个计时器。时间 1 和时间 2 均由用户手动输入。
Thanks in advance for your help.
在此先感谢您的帮助。
回答by iamamac
The datetime
and timedelta
class from the built-in datetime
module is what you need.
内置模块中的datetime
andtimedelta
类datetime
正是您所需要的。
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)
回答by Alex Martelli
Simplest and most direct may be something like:
最简单和最直接的可能是这样的:
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)
E.g., a typical run might be:
例如,典型的运行可能是:
$ python ti.py
Enter time-1 (hh:mm): 01:12
Enter time-2 (hh:mm): 18:59
Difference: 17 hours and 47 minutes
回答by Tor Valamo
Here's a timer for timing code execution. Maybe you can use it for what you want. time() returns the current time in seconds and microseconds since 1970-01-01 00:00:00.
这是一个用于计时代码执行的计时器。也许你可以用它来做你想要的。time() 返回自 1970-01-01 00:00:00 以来的当前时间(以秒和微秒为单位)。
from time import time
t0 = time()
# do stuff that takes time
print time() - t0
回答by David R Tribble
Assuming that the user is entering strings like "01:12"
, you need to convert (as well as validate) those strings into the number of minutes since 00:00
(e.g., "01:12"
is 1*60+12
, or 72 minutes), then subtract one from the other. You can then convert the difference in minutes back into a string of the form hh:mm
.
假设用户输入类似 的字符串"01:12"
,您需要将这些字符串转换(以及验证)为自此以来的分钟数00:00
(例如,"01:12"
是1*60+12
或 72 分钟),然后从另一个中减去一个。然后,您可以将以分钟为单位的差异转换回形式为 的字符串hh:mm
。