【问题标题】:Time stamp conversion and deltatime with a decimal error带有十进制错误的时间戳转换和 deltatime
【发布时间】:2016-08-20 20:44:43
【问题描述】:

我们正在处理 CSV 文件中的时间戳列并遇到错误,因为 CSV 时间戳的格式如下:30:50.0,我们相当确定它的小时和分钟。秒的小数点,但每个小数点都是 0。我们正在使用此代码来读取和获取时间:

fmt = "%H:%M.0"

但是,它返回此错误: ValueError:时间数据 '30:50.0' 与格式 '%H:%M.0' 不匹配 使用返回的类似错误:'%H:%M.%S' 最后,当仅使用 '%H:%M 时,我们会收到此错误: 未转换的数据仍然存在:.0 我们对如何编辑或以其他方式读取时间码一无所知。无需手动编辑 CSV 文件。

# Import moduels for use
from datetime import datetime as dt
import itertools

# Creating a function that will get the total difference in time between each point
def compute_delta_time(timelist):
    timetotal = []
    a, b = itertools.tee(timelist)
    next(b, None)
    fmt = "%H:%M.0"
    for start, end in itertools.izip(a,b):  
        timetotal.append((dt.strptime(end, fmt) - dt.strptime(start, fmt)).total_seconds())
    return timetotal

这是我们的全部功能。

【问题讨论】:

    标签: python csv decimal timedelta


    【解决方案1】:

    %H 必须在 0..23 范围内。您可以手动将持续时间字符串解析为@PfunnyGuy suggested:

    def to_seconds(duration_string):
        """'30:50.0' -> 111000"""
        hm, dot, seconds = duration_string.partition('.')
        hours, minutes = map(int, hm.split(':'))
        return (hours * 60 + minutes) * 60 + (int(seconds) if dot else 0)
    

    例子:

    durations = map(to_seconds, ["25:01", "30:50.0"])
    time_diff =  [end - start for start, end in zip(durations, durations[1:])]
    # ->  [20940]
    

    【讨论】:

      【解决方案2】:

      你可以暴力破解:

      >>> x="30:50.0"
      >>> h,mm=x.split(":")
      >>> m,s=mm.split(".")
      >>> int(h)
      30
      >>> int(m)
      50
      >>> int(s)
      0
      

      它很丑,但可行。

      另外,我建议您在帖子中添加标签“python”。

      【讨论】:

        猜你喜欢
        • 2018-02-27
        • 2015-03-12
        • 1970-01-01
        • 1970-01-01
        • 2012-10-20
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多