【问题标题】:Transform time span strings to seconds in real number form以实数形式将时间跨度字符串转换为秒
【发布时间】:2026-01-08 04:30:01
【问题描述】:

我有一个熊猫,其字符串的时间跨度格式为 DD.hh:mm:ss.nnnnnnn。正在寻找将其转换为可存储为实数的秒数的方法。 数据框:

duration {'13:11:21.2600000','12.18:52:17.0640000','12.18:52:17.0640000','4.07:28:42.7160000','4.09:30:34.1700000'}

我尝试使用:

for dur in duration:
    secs= dur.total_seconds()
    rlist.append(secs)

但出现以下错误:

AttributeError: 'datetime.time' 对象没有属性 'total_seconds'

使用正则表达式成功地使用了这种低效的方式:

df=df.astype(str)
daySearch="\.\d\d:"
sep='.'
for i in duration:
    if re.search(daySearch,i):
       day,dur,micros=i.split('.')
       h, m, s = dur.split(':')
       secs_int=(int(day) * 86400) + (int(h) * 3600 + int(m) * 60 + int(s))
       secs=str(secs_int)+sep+micros
       print(secs)
    else:
        dur, micros = i.split('.')
        h, m, s = dur.split(':')
        secs_int = int(h) * 3600 + int(m) * 60 + int(s)
        secs = str(secs_int) + sep + micros
        print(secs)

【问题讨论】:

    标签: python python-3.x string time duration


    【解决方案1】:

    首先使用strptime将字符串转换为日期时间实例

    datetime.strptime(date_string, format)
    

    然后转换为总秒数 w.r.t.一些参考时间。

    (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
    

    【讨论】:

    • 得到以下错误:ValueError: time data '13:11:21.2600000' does not match format '%m/%d %H:%M:%S.%f' 将转换它到日期时间
    • 格式字符串不匹配。您应该使用匹配的格式字符串。 %H:%M:%:S.%f