【问题标题】:How to convert a time string to seconds?如何将时间字符串转换为秒?
【发布时间】:2012-05-26 16:23:00
【问题描述】:

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

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

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

【问题讨论】:

  • 你不需要使用datatime.datetime.strptimetime.strptime 也可以,只是由于某种原因不在文档中......

标签: python time python-datetime


【解决方案1】:
>>> 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

【讨论】:

    【解决方案2】:

    我认为更pythonic的方式是:

    timestr = '00:04:23'
    
    ftr = [3600,60,1]
    
    sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])
    

    输出为 263 秒。

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

    【讨论】:

    • 列表推导更 Pythonic。所以sum([a*b for a,b in zip(ftr, [int(i) for i in timestr.split(":")])]) 会更pythonic。
    • 感谢 Le Vieux Gildas.. 它应该是 263.. ftr 不应该是 [3600,60,0].. 它必须是 [3600,60,1]... 谢谢 agian
    • 您忘记将字符串转换为整数 => lambda x : sum([int(x)*int(y) for x,y in zip([3600,60,1],x .split(":"))])
    【解决方案3】:

    没有进口

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

    【讨论】:

    • 优秀的答案,小的调整能够正确处理 mm:ss 和 hh:mm:ss 格式,只需反转拆分即可。sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time.split(":"))))
    【解决方案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】:

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

      【讨论】:

        【解决方案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
        

        【讨论】:

        • 添加解释通常很有帮助
        【解决方案7】:

        总是要手动解析

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

        【讨论】:

        • 我讨厌在 Python 中手工操作:p
        【解决方案8】:
        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

        【讨论】:

          【解决方案9】:

          灵感来自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(":"))))
          

          【讨论】:

            【解决方案10】:
            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
            

            【讨论】:

              【解决方案11】:

              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]
              

              【讨论】:

                【解决方案12】:

                为什么不使用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)
                

                【讨论】:

                  【解决方案13】:

                  .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
                  

                  【讨论】:

                    猜你喜欢
                    • 2011-07-04
                    • 2013-02-17
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-07-11
                    • 1970-01-01
                    • 2016-10-02
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多