在python中将时间字符串转换为秒

时间:2012-05-19 08:43:57

标签: python time

我需要将以下格式给出的时间值字符串转换为秒。我正在使用python2.6

例如:

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'

有人可以告诉我这是如何解决的吗?

编辑:

我认为

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

给出正确的值..我使用了错误的模块

12 个答案:

答案 0 :(得分:52)

对于Python 2.7:

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

答案 1 :(得分:28)

我认为会有更多的pythonic方式:

timestr = '00:04:23'

ftr = [3600,60,1]

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

输出为263秒。

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

答案 2 :(得分:13)

没有进口

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

答案 3 :(得分:4)

看起来你愿意剥掉几分之一......问题是你不能使用'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)
>>>

答案 4 :(得分:4)

要获得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

答案 5 :(得分:4)

struct WidgetTestEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        
        VStack {
            HStack(spacing: 100){
                Text("Favourite").foregroundColor(.white).font(.system(size: 16, weight: .bold, design: .default))
                Image("Label").resizable().frame(width: 80, height: 15, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                
            }.frame(maxWidth: .infinity, maxHeight: 50, alignment: .center).background(Color.black).offset(y: -9)
            
            
            HStack {
                Spacer()
                Button(action: {}) {
                    Image("").resizable().frame(width: 70, height: 70)
                        .cornerRadius(10)
                        .background(Color(red: 0.218, green: 0.215, blue: 0.25))
                }.cornerRadius(10).onTapGesture {
                    let a = ViewController()
                    a.data.text = "Tap"
                }

                Button(action: {}) {
                    Image("").resizable().frame(width: 70, height: 70)
                        .cornerRadius(10)
                        .background(Color(red: 0.218, green: 0.215, blue: 0.25))
                }.cornerRadius(10).onTapGesture {
                    let a = ViewController()
                    a.data.text = "Tap"
                }

                Button(action: {}) {
                    Image("").resizable().frame(width: 70, height: 70)
                        .cornerRadius(10)
                        .background(Color(red: 0.218, green: 0.215, blue: 0.25))
                }.cornerRadius(10).onTapGesture {
                    let a = ViewController()
                    a.data.text = "Tap"
                }

                Button(action: {}) {
                    Image("").resizable().frame(width: 70, height: 70)
                        .cornerRadius(10)
                        .background(Color(red: 0.218, green: 0.215, blue: 0.25))
                }.cornerRadius(10).onTapGesture {
                    let a = ViewController()
                    a.data.text = "Tap"
                }

                Spacer().frame(width: 10, height: 10, alignment: .center)
            }.background(Color(red: 0.118, green: 0.118, blue: 0.15)).offset(y: -9)
            
            
        }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center).background(Color(red: 0.118, green: 0.118, blue: 0.15))
    }
}

答案 6 :(得分:3)

总是手工解析

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

答案 7 :(得分:2)

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

答案 8 :(得分:0)

受到sverrir-sigmundarson's评论的启发:

def time_to_sec(time_str):
    return sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time_str.split(":"))))

答案 9 :(得分: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

答案 10 :(得分: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]

答案 11 :(得分: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)