如何计算两个时间字符串之间的时间间隔 [英] How to calculate the time interval between two time strings

查看:80
本文介绍了如何计算两个时间字符串之间的时间间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个时间,一个开始时间和一个停止时间,格式为 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?

推荐答案

是的,绝对日期时间 正是您所需要的.具体来说,datetime.strptime() 方法将字符串解析为 datetime 对象.

Yes, definitely datetime is what you need here. Specifically, the datetime.strptime() method, which parses a string into a datetime 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)

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

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.

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

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
    )

(当然你需要在某处包含from datetime import timedelta).感谢 J.F. Sebastian 指出这个用例.

(of course you need to include from datetime import timedelta somewhere). Thanks to J.F. Sebastian for pointing out this use case.

这篇关于如何计算两个时间字符串之间的时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆