如何将时间字符串转换为秒?

80

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

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模块,但是

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
дҪ дёҚйңҖиҰҒдҪҝз”Ёdatatime.datetime.strptimeпјҢtime.strptimeеҗҢж ·йҖӮз”ЁпјҢеҸӘжҳҜеҮәдәҺжҹҗз§ҚеҺҹеӣ жІЎжңүеңЁж–ҮжЎЈдёӯи®°еҪ•дёӢжқҘ... - Josiah
13个回答

84
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

44

我认为更符合 Python 风格的方法是:

timestr = '00:04:23'

ftr = [3600,60,1]

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

输出为263秒。

我会很感兴趣看到是否有人能够进一步简化它。


2
列表推导式更符合Python风格。因此,sum([a*b for a,b in zip(ftr, [int(i) for i in timestr.split(":")])])会更符合Python风格。 - inspectorG4dget
2
谢谢Le Vieux Gildas。应该是263。ftr不应该是[3600,60,0],而是[3600,60,1]。再次感谢。 - user1721943
你忘了将字符串转换为整数 => lambda x : sum([int(x)*int(y) for x,y in zip([3600,60,1],x.split(":"))]) - greendino

34

不使用导入

time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":"))) 

12
优秀的回答,为了能够正确处理 mm:ss 和 hh:mm:ss 两种格式,只需反转拆分即可。sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time.split(":")))) - Sverrir Sigmundarson
1
对于处理秒的小调整(将其转换为浮点数而不是整数),可以使用以下代码:sum(x * float(t) for x, t in zip([1, 60, 3600], reversed(time.split(":")))) - John

13

获取 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

在Python 2.6中模拟.total_seconds()方法:

>>> from __future__ import division
>>> ((td.days * 86400 + td.seconds) * 10**6 + td.microseconds) / 10**6
111669.0

8
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

4
添加解释通常是有帮助的。 - con

6

看起来你想要去掉小数秒,但使用%I时不能将小时表示为“00”。

>>> 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)
>>>

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
>>> 

4
我讨厌在 Python 中手动操作:p - jamylak

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


4

.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

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(":"))))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接