如何计算两个时间字符串之间的时间间隔

时间:2022-06-06 20:40:53

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.

我有两次,一个开始和一个停止时间,格式为10:33:26(HH:MM:SS)。我需要两次之间的区别。我一直在浏览Python的文档和在线搜索,我想它会与日期时间和/或时间模块有关。我无法让它正常工作,并且在涉及日期时只能查找如何执行此操作。

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?

对于平均,我应该转换为秒然后平均吗?

9 个解决方案

#1


129  

Yes, definitely datetime is what you need here. Specifically, the strptime function, which parses a string into a time object.

是的,绝对是日期时间你需要的。具体来说,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)

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.

这会得到一个包含两次之间差异的timedelta对象。你可以做任何你想做的事,例如将其转换为秒或将其添加到另一个日期时间。

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:

如果结束时间早于开始时间,则返回否定结果,例如s1 = 12:00:00和s2 = 05:00:00。如果您希望代码假设在这种情况下间隔跨越午夜(即它应该假设结束时间从不早于开始时间),则可以将以下行添加到上面的代码中:

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.

(当然你需要从datetime导入timedelta包含在某个地方)。感谢J.F. Sebastian指出这个用例。

#2


85  

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)

#3


9  

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:

表示Python中时差的结构称为timedelta。如果你有start_time和end_time作为日期时间类型,你可以使用 - 运算符来计算差异:

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.

你应该在转换为特殊字符串格式之前这样做(例如在start_time.strftime(...)之前)。如果您已经有字符串表示,则需要使用strptime方法将其转换回时间/日期时间。

#4


9  

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):

这是一个支持查找差异的解决方案,即使结束时间小于开始时间(午夜时间间隔),例如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())

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.:

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

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.

mean()结果也是timedelta()对象,你可以转换为秒(td.total_seconds()方法(自Python 2.7)),小时(td / timedelta(小时= 1)(Python 3))等。

#5


6  

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()

这个论坛使用time.mktime()

#6


3  

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.

我喜欢这个人怎么做 - https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps。不确定它是否有一些缺点。

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.

关于这个问题,你仍然需要像其他人之前所说的那样使用datetime.strptime()。

#7


1  

Both time and datetime have a date component.

time和datetime都有一个日期组件。

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).

通常,如果您只是处理时间部分,则提供默认日期。如果您只是对差异感兴趣并且知道两个时间都在同一天,那么为每个设置到今天的日期构建一个日期时间,并从停止时间减去开始以获得间隔(timedelta)。

#8


1  

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.

看一下datetime模块和timedelta对象。你最终应该为开始和停止时间构建一个datetime对象,当你减去它们时,你得到一个timedelta。

#9


1  

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

#1


129  

Yes, definitely datetime is what you need here. Specifically, the strptime function, which parses a string into a time object.

是的,绝对是日期时间你需要的。具体来说,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)

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.

这会得到一个包含两次之间差异的timedelta对象。你可以做任何你想做的事,例如将其转换为秒或将其添加到另一个日期时间。

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:

如果结束时间早于开始时间,则返回否定结果,例如s1 = 12:00:00和s2 = 05:00:00。如果您希望代码假设在这种情况下间隔跨越午夜(即它应该假设结束时间从不早于开始时间),则可以将以下行添加到上面的代码中:

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.

(当然你需要从datetime导入timedelta包含在某个地方)。感谢J.F. Sebastian指出这个用例。

#2


85  

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)

#3


9  

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:

表示Python中时差的结构称为timedelta。如果你有start_time和end_time作为日期时间类型,你可以使用 - 运算符来计算差异:

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.

你应该在转换为特殊字符串格式之前这样做(例如在start_time.strftime(...)之前)。如果您已经有字符串表示,则需要使用strptime方法将其转换回时间/日期时间。

#4


9  

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):

这是一个支持查找差异的解决方案,即使结束时间小于开始时间(午夜时间间隔),例如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())

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.:

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

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.

mean()结果也是timedelta()对象,你可以转换为秒(td.total_seconds()方法(自Python 2.7)),小时(td / timedelta(小时= 1)(Python 3))等。

#5


6  

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()

这个论坛使用time.mktime()

#6


3  

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.

我喜欢这个人怎么做 - https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps。不确定它是否有一些缺点。

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.

关于这个问题,你仍然需要像其他人之前所说的那样使用datetime.strptime()。

#7


1  

Both time and datetime have a date component.

time和datetime都有一个日期组件。

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).

通常,如果您只是处理时间部分,则提供默认日期。如果您只是对差异感兴趣并且知道两个时间都在同一天,那么为每个设置到今天的日期构建一个日期时间,并从停止时间减去开始以获得间隔(timedelta)。

#8


1  

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.

看一下datetime模块和timedelta对象。你最终应该为开始和停止时间构建一个datetime对象,当你减去它们时,你得到一个timedelta。

#9


1  

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