【问题标题】:Python: Arithmetic operations with miliseconds in string formatPython:以毫秒为单位的字符串格式的算术运算
【发布时间】:2021-12-15 20:59:05
【问题描述】:

我有当前为strings的时间变量:

Time
18:29:36.809889
18:30:16.291965  

我想计算这两个值之间的差异(可能是一个浮点数)。 如何解析字符串并执行操作?

谢谢!

【问题讨论】:

标签: python string parsing data-science


【解决方案1】:

这段代码会以秒为单位产生差异

time1 = "18:29:36.809889"
time2 = "18:30:16.291965"
hr1, min1, sec1  = time1.split(":")
hr2, min2, sec2 = time2.split(":")
ms1 = float(sec1) + int(min1)*60 + int(hr1)*60*60
ms2 = float(sec2) + int(min2)*60 + int(hr2)*60*60
print(abs(ms2 - ms1))

但是,我必须补充一点,使用字符串操作计算时差不是正确的方法。无论您从哪里获取时间戳,都可以将它们转换为纪元时间,从而更轻松地获得差异。

【讨论】:

    【解决方案2】:

    将时间字符串转换为 datetime 实例,然后将差值作为 timedelta 对象,您可以从中获取浮点值作为总秒数。

    from datetime import datetime
    a = '18:29:36.809889'
    b = '18:30:16.291965'
    date1 = datetime.strptime(a, '%H:%M:%S.%f')
    date2 = datetime.strptime(b, '%H:%M:%S.%f')
    delta = date2 - date1
    print(delta)
    print(delta.total_seconds(), "seconds")
    

    输出:

    0:00:39.482076
    39.482076 seconds
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2014-02-06
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多