问题:如何计算两个时间字符串之间的时间间隔
我有两次,开始时间和停止时间,格式为10:33:26(HH:MM:SS)。我需要两次之间的区别。我一直在浏览Python文档并在线搜索,我想这可能与datetime和/或time模块有关。我无法使其正常工作,并且仅在涉及约会时才继续寻找如何执行此操作。
最终,我需要计算多个持续时间的平均值。我得到了可以工作的时差,并将它们存储在列表中。我现在需要计算平均值。我正在使用正则表达式解析原始时间,然后进行区别。
对于平均,我应该转换为秒然后平均吗?
I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I’ve been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can’t get it to work properly and keep finding only how to do this when a date is involved.
Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I’m storing them in a list. I now need to calculate the average. I’m using regular expressions to parse out the original times and then doing the differences.
For the averaging, should I convert to seconds and then average?
回答 0
是的,datetime
这里绝对是您所需要的。具体来说,是strptime
将字符串解析为时间对象的函数。
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
这样就得到了一个timedelta
包含两次差异的对象。您可以执行此操作,例如将其转换为秒或将其添加到另一个datetime
。
如果结束时间早于开始时间,则返回否定结果,例如s1 = 12:00:00
和s2 = 05:00:00
。如果在这种情况下,如果您希望代码假定间隔经过午夜(即应该假定结束时间永远不会早于开始时间),则可以在上面的代码中添加以下几行:
if tdelta.days < 0:
tdelta = timedelta(days=0,
seconds=tdelta.seconds, microseconds=tdelta.microseconds)
(当然,您需要在from datetime import timedelta
某处添加)。感谢JF Sebastian指出了这个用例。
Yes, definitely datetime
is what you need here. Specifically, the strptime
function, which parses a string into a time object.
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
That gets you a timedelta
object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime
.
This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00
and s2 = 05:00:00
. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:
if tdelta.days < 0:
tdelta = timedelta(days=0,
seconds=tdelta.seconds, microseconds=tdelta.microseconds)
(of course you need to include from datetime import timedelta
somewhere). Thanks to J.F. Sebastian for pointing out this use case.
回答 1
尝试一下-在安排短期事件时非常有效。如果花费了一个多小时,那么最终的显示可能会需要一些友好的格式。
import time
start = time.time()
time.sleep(10) # or do something more productive
done = time.time()
elapsed = done - start
print(elapsed)
返回时差作为经过的秒数。
Try this — it’s efficient for timing short-term events. If something takes more than an hour, then the final display probably will want some friendly formatting.
import time
start = time.time()
time.sleep(10) # or do something more productive
done = time.time()
elapsed = done - start
print(elapsed)
The time difference is returned as the number of elapsed seconds.
回答 2
即使结束时间小于开始时间(超过午夜间隔),例如23:55:00-00:25:00
(半小时),这也是一种支持找到差异的解决方案:
#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta
def time_diff(start, end):
if isinstance(start, datetime_time): # convert to datetime
assert isinstance(end, datetime_time)
start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
if start <= end: # e.g., 10:33:26-11:15:49
return end - start
else: # end < start e.g., 23:55:00-00:25:00
end += timedelta(1) # +day
assert end > start
return end - start
for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
print(time_diff(s, e))
assert time_diff(s, e) == time_diff(s.time(), e.time())
输出量
0:42:23
0:30:00
time_diff()
返回一个timedelta对象,您可以将其直接(作为序列的一部分)传递给mean()
函数,例如:
#!/usr/bin/env python
from datetime import timedelta
def mean(data, start=timedelta(0)):
"""Find arithmetic average."""
return sum(data, start) / len(data)
data = [timedelta(minutes=42, seconds=23), # 0:42:23
timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds
该mean()
结果也是timedelta()
对象,可转换为秒(td.total_seconds()
方法(因为Python 2.7)),小时(td / timedelta(hours=1)
(Python 3中)),等等。
Here’s a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as 23:55:00-00:25:00
(a half an hour duration):
#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta
def time_diff(start, end):
if isinstance(start, datetime_time): # convert to datetime
assert isinstance(end, datetime_time)
start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
if start <= end: # e.g., 10:33:26-11:15:49
return end - start
else: # end < start e.g., 23:55:00-00:25:00
end += timedelta(1) # +day
assert end > start
return end - start
for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
print(time_diff(s, e))
assert time_diff(s, e) == time_diff(s.time(), e.time())
Output
0:42:23
0:30:00
time_diff()
returns a timedelta object that you can pass (as a part of the sequence) to a mean()
function directly e.g.:
#!/usr/bin/env python
from datetime import timedelta
def mean(data, start=timedelta(0)):
"""Find arithmetic average."""
return sum(data, start) / len(data)
data = [timedelta(minutes=42, seconds=23), # 0:42:23
timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds
The mean()
result is also timedelta()
object that you can convert to seconds (td.total_seconds()
method (since Python 2.7)), hours (td / timedelta(hours=1)
(Python 3)), etc.
回答 3
表示Python中时差的结构称为timedelta。如果有start_time
和end_time
作为datetime
类型,则可以使用以下-
运算符来计算差异:
diff = end_time - start_time
您应该在转换为特定的字符串格式之前执行此操作(例如,在start_time.strftime(…)之前)。如果您已经有了字符串表示形式,则需要使用strptime方法将其转换回时间/日期时间。
Structure that represent time difference in Python is called timedelta. If you have start_time
and end_time
as datetime
types you can calculate the difference using -
operator like:
diff = end_time - start_time
you should do this before converting to particualr string format (eg. before start_time.strftime(…)). In case you have already string representation you need to convert it back to time/datetime by using strptime method.
回答 4
该网站说尝试:
import datetime as dt
start="09:35:23"
end="10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt)
diff.seconds/60
本论坛使用time.mktime()
This site says to try:
import datetime as dt
start="09:35:23"
end="10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt)
diff.seconds/60
This forum uses time.mktime()
回答 5
I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps.
Not sure if it has some cons.
But looks neat for me :)
from datetime import datetime
from dateutil.relativedelta import relativedelta
t_a = datetime.now()
t_b = datetime.now()
def diff(t_a, t_b):
t_diff = relativedelta(t_b, t_a) # later/end time comes first!
return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)
Regarding to the question you still need to use datetime.strptime()
as others said earlier.
回答 6
试试这个
import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time
输出:
0:00:05
Try this
import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time
OUTPUT :
0:00:05
回答 7
import datetime as dt
from dateutil.relativedelta import relativedelta
start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, "%H:%M:%S")
end_dt = dt.datetime.strptime(end, "%H:%M:%S")
timedelta_obj = relativedelta(start_dt, end_dt)
print(
timedelta_obj.years,
timedelta_obj.months,
timedelta_obj.days,
timedelta_obj.hours,
timedelta_obj.minutes,
timedelta_obj.seconds,
)
结果:0 0 0 0 -47 -37
import datetime as dt
from dateutil.relativedelta import relativedelta
start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, "%H:%M:%S")
end_dt = dt.datetime.strptime(end, "%H:%M:%S")
timedelta_obj = relativedelta(start_dt, end_dt)
print(
timedelta_obj.years,
timedelta_obj.months,
timedelta_obj.days,
timedelta_obj.hours,
timedelta_obj.minutes,
timedelta_obj.seconds,
)
result:
0 0 0 0 -47 -37
回答 8
两者time
和datetime
都有日期部分。
通常,如果您只处理时间部分,则需要提供默认日期。如果您只是对两者之间的差异感兴趣,并且知道两个时间都在同一天,datetime
则为每个日期构造一个a ,并将日期设置为今天,然后从停止时间中减去开始时间以获取时间间隔(timedelta
)。
Both time
and datetime
have a date component.
Normally if you are just dealing with the time part you’d supply a default date. If you are just interested in the difference and know that both times are on the same day then construct a datetime
for each with the day set to today and subtract the start from the stop time to get the interval (timedelta
).
回答 9
看一下datetime模块和timedelta对象。您应该最终为开始时间和结束时间构造一个datetime对象,然后减去它们,您将获得一个timedelta。
Take a look at the datetime module and the timedelta objects. You should end up constructing a datetime object for the start and stop times, and when you subtract them, you get a timedelta.
回答 10
如果您只是对24小时以下的时间感兴趣,请简明扼要。您可以根据需要在return语句中格式化输出:
import datetime
def elapsed_interval(start,end):
elapsed = end - start
min,secs=divmod(elapsed.days * 86400 + elapsed.seconds, 60)
hour, minutes = divmod(min, 60)
return '%.2d:%.2d:%.2d' % (hour,minutes,secs)
if __name__ == '__main__':
time_start=datetime.datetime.now()
""" do your process """
time_end=datetime.datetime.now()
total_time=elapsed_interval(time_start,time_end)
Concise if you are just interested in the time elapsed that is under 24 hours. You can format the output as needed in the return statement :
import datetime
def elapsed_interval(start,end):
elapsed = end - start
min,secs=divmod(elapsed.days * 86400 + elapsed.seconds, 60)
hour, minutes = divmod(min, 60)
return '%.2d:%.2d:%.2d' % (hour,minutes,secs)
if __name__ == '__main__':
time_start=datetime.datetime.now()
""" do your process """
time_end=datetime.datetime.now()
total_time=elapsed_interval(time_start,time_end)