68

我需要将以下格式给出的时间值字符串转换为秒,例如:

1.'00:00:00,000' -> 0 seconds

2.'00:00:10,000' -> 10 seconds

3.'00:01:04,000' -> 64 seconds

4.'01:01:09,000' -> 3669 seconds

我需要使用正则表达式来做到这一点吗?我尝试使用时间模块,但是

time.strptime('00:00:00,000','%I:%M:%S')

抛出:

ValueError: time data '00:00:00,000' does not match format '%I:%M:%S'

编辑

看起来像这样:

from datetime import datetime
pt = datetime.strptime(timestring,'%H:%M:%S,%f')
total_seconds = pt.second + pt.minute*60 + pt.hour*3600

给出正确的结果。我只是使用了错误的模块。

4

13 回答 13

73
>>> import datetime
>>> import time
>>> x = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')
>>> datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()
60.0
于 2012-05-19T09:07:29.187 回答
43

我认为更pythonic的方式是:

timestr = '00:04:23'

ftr = [3600,60,1]

sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])

输出为 263 秒。

我很想看看是否有人可以进一步简化它。

于 2012-10-05T04:34:55.920 回答
30

没有进口

time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":"))) 
于 2016-12-20T22:56:31.790 回答
11

要得到timedelta(),你应该减去1900-01-01

>>> from datetime import datetime
>>> datetime.strptime('01:01:09,000', '%H:%M:%S,%f')
datetime.datetime(1900, 1, 1, 1, 1, 9)
>>> td = datetime.strptime('01:01:09,000', '%H:%M:%S,%f') - datetime(1900,1,1)
>>> td
datetime.timedelta(0, 3669)
>>> td.total_seconds() # 2.7+
3669.0

%H上面暗示输入小于一天,支持一天以上的时差:

>>> import re
>>> from datetime import timedelta
>>> td = timedelta(**dict(zip("hours minutes seconds milliseconds".split(),
...                           map(int, re.findall('\d+', '31:01:09,000')))))
>>> td
datetime.timedelta(1, 25269)
>>> td.total_seconds()
111669.0

.total_seconds()在 Python 2.6 上进行模拟:

>>> from __future__ import division
>>> ((td.days * 86400 + td.seconds) * 10**6 + td.microseconds) / 10**6
111669.0
于 2015-09-12T12:00:03.447 回答
6

看起来你愿意剥夺几分之一秒......问题是你不能使用'00'作为小时%I

>>> time.strptime('00:00:00,000'.split(',')[0],'%H:%M:%S')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>>
于 2012-05-19T08:50:01.397 回答
6
def time_to_sec(t):
   h, m, s = map(int, t.split(':'))
   return h * 3600 + m * 60 + s

t = '10:40:20'
time_to_sec(t)  # 38420
于 2021-02-17T10:53:05.233 回答
5

总是有手工解析

>>> import re
>>> ts = ['00:00:00,000', '00:00:10,000', '00:01:04,000', '01:01:09,000']
>>> for t in ts:
...     times = map(int, re.split(r"[:,]", t))
...     print t, times[0]*3600+times[1]*60+times[2]+times[3]/1000.
... 
00:00:00,000 0.0
00:00:10,000 10.0
00:01:04,000 64.0
01:01:09,000 3669.0
>>> 
于 2012-05-19T08:54:02.847 回答
4
import time
from datetime import datetime

t1 = datetime.now().replace(microsecond=0)
time.sleep(3)
now = datetime.now().replace(microsecond=0)
print((now - t1).total_seconds())

结果:3.0

于 2018-08-30T21:03:17.463 回答
2

灵感来自sverrir-sigmundarson 的评论:

def time_to_sec(time_str):
    return sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time_str.split(":"))))
于 2019-05-06T10:13:24.503 回答
0
def time_to_sec(time):
    sep = ','
    rest = time.split(sep, 1)[0]
    splitted = rest.split(":")
    emel = len(splitted) - 1
    i = 0
    summa = 0
    for numb in splitted:
        szor = 60 ** (emel - i)
        i += 1
        summa += int(numb) * szor
    return summa
于 2020-09-20T22:15:59.243 回答
0

HH:MM:SS 和 MM:SS 的动态解决方案。如果要处理命令,请使用split(',')除以 1000 或其他内容,然后添加。

_time = 'SS'
_time = 'MM:SS'
_time = 'HH:MM:SS'
seconds = sum(int(x) * 60 ** i for i, x in enumerate(reversed(_time.split(':'))))
# multiple timestamps
_times = ['MM:SS', 'HH:MM:SS', 'SS']
_times = [sum(int(x) * 60 ** i for i, x in enumerate(reversed(_time.split(':')))) for _time in times]
于 2021-04-17T17:55:48.740 回答
0

为什么不使用functools.reduce

from functools import reduce

def str_to_seconds(t):
    reduce(lambda prev, next: prev * 60 + next, [float(x) for x in t.replace(',', '.').split(":")], 0)

一个功能,适用10,4009:12,4002:08:14,59。如果您使用.而不是,十进制符号,它会更简单:

def str_to_seconds(t):
    reduce(lambda prev, next: prev * 60 + next, [float(x) for x in t.split(":")], 0)
于 2021-06-10T23:32:29.650 回答
0

.total_seconds()似乎直截了当

from datetime import datetime

FMT = '%H:%M:%S.%f'

#example
s2 = '11:01:49.897'
s1 = '10:59:26.754'

# calculate difference
pt = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

# compute seconds number (answer)
total_seconds = pt.total_seconds()
# output: 143.143
于 2022-01-13T13:36:24.960 回答