【问题标题】:How to convert an H:MM:SS time string to seconds in Python?如何在 Python 中将 H:MM:SS 时间字符串转换为秒?
【发布时间】:2011-09-18 04:05:49
【问题描述】:

基本上我有这个问题的反面:Python Time Seconds to h:m:s

我有一个格式为 H:MM:SS 的字符串(分钟和秒总是 2 位数字),我需要它表示的整数秒数。我如何在 python 中做到这一点?

例如:

  • "1:23:45" 将产生 5025 的输出
  • "0:04:15" 将产生 255 的输出
  • "0:00:25" 将产生 25 的输出

【问题讨论】:

标签: python


【解决方案1】:

扩展@FMc 的解决方案,它体现了Horner's method 的一半。霍纳法的优点:跳过倒序,避免power计算。

from functools import reduce

timestamp = "1:23:45"
seconds = reduce(lambda s, d: s * 60 + int(d), timestamp.split(":"), 0)

或者,如果你不喜欢 reduceas does Guido van Rossum 和 @0xc0de below):

timestamp = "1:23:45"
seconds = 0
for d in timestamp.split(":"):
    seconds = seconds * 60 + int(d)

如果您更喜欢zip(@nathan-rice below 也是如此):

from itertools import accumulate, repeat
from operator import mul

def timestamp_to_seconds(t):
    return sum(int(n) * m for n, m in
       zip(reversed(t.split(":")), accumulate(repeat(60), func=mul, initial=1)))

【讨论】:

  • 在性能方面向前迈进了一步,但在可读性方面可能会倒退一步,除非您的所有同事/同事的代码阅读器都具有 reduced 的可读性。 +1 对于这些情况,我不是 reduce() 的粉丝,我更愿意避免这些。
【解决方案2】:

对于 %H:%M:%S.%f

def get_sec(time_str):
    h, m, s = time_str.split(':')
    return int(h) * 3600 + int(m) * 60 + float(s)

【讨论】:

    【解决方案3】:

    没有太多检查,假设它是“SS”或“MM:SS”或“HH:MM:SS”(虽然不一定每个部分两位数):

    def to_seconds(timestr):
        seconds= 0
        for part in timestr.split(':'):
            seconds= seconds*60 + int(part, 10)
        return seconds
    
    >>> to_seconds('09')
    9
    >>> to_seconds('2:09')
    129
    >>> to_seconds('1:02:09')
    3729
    

    这是 FMc 答案的不同“拼写”:)

    【讨论】:

    • 真的很有用。谢谢。我喜欢你考虑到只包含秒或分钟的较短字符串...... ?
    • 这是最好的解决方案。怎么票数这么低!?它将缺少minuteshours 部分的字符串考虑在一个简洁的单一函数中,并且不使用任何额外的库。赞一个!
    【解决方案4】:

    在 Pandas 中使用 @JayRizzo 的酷函数和列表理解:

    def get_sec(time_str):
        """Get Seconds from time."""
        h, m, s = time_str.split(':')
        return int(h) * 3600 + int(m) * 60 + int(s)
    
    df['secs']=[get_sec(x) for x in df['original_time_string']]
    

    【讨论】:

      【解决方案5】:

      只是对taskinoor的热烈响应的简单概括

      就我的问题而言,格式类似,但包括 AM 或 PM。

      格式为“HH:MM:SS AM”或“HH:MM:SS PM”

      对于这种情况,函数变为:

      def get_sec(time_str):
      """Get Seconds from time."""
      if 'AM' in time_str:
          time_str = time_str.strip('AM')
          h, m, s = time_str.split(':')
          seconds = int(h) * 3600 + int(m) * 60 + int(s)
      if 'PM' in time_str:
          time_str = time_str.strip('PM')
          h, m, s = time_str.split(':')
          seconds = (12 + int(h)) * 3600 + int(m) * 60 + int(s)
      
      return seconds 
      

      【讨论】:

        【解决方案6】:
        ts = '1:23:45'
        secs = sum(int(x) * 60 ** i for i, x in enumerate(reversed(ts.split(':'))))
        print(secs)
        

        【讨论】:

        • 这是一个非常有趣的技术。感谢分享。
        • 那个双星操作员是做什么的?
        • @hughes 求幂。
        • 这个高级代码也能正确处理sm:s字符串,比如“53”和“2:41”
        【解决方案7】:

        使用datetime 模块也是可行的并且更健壮

        import datetime as dt
        
        def get_total_seconds(stringHMS):
           timedeltaObj = dt.datetime.strptime(stringHMS, "%H:%M:%S") - dt.datetime(1900,1,1)
           return timedeltaObj.total_seconds()
        

        datetime.strptime 根据格式 %H:%M:%S 解析字符串,并创建日期时间对象为 1900 年、1 月、1 天、小时 H、分钟 M 和秒 S。

        这就是为什么要得到总秒数需要减去年、月和日。

        print(get_total_seconds('1:23:45'))
        >>> 5025.0
        
        print(get_total_seconds('0:04:15'))
        >>> 255.0
        
        print(get_total_seconds('0:00:25'))
        >>>25.0
        

        【讨论】:

        • 这对我有用。我用 "%H:%M:%S.%f" 代替处理小数秒
        【解决方案8】:
        def get_sec(time_str):
            """Get Seconds from time."""
            h, m, s = time_str.split(':')
            return int(h) * 3600 + int(m) * 60 + int(s)
        
        
        print(get_sec('1:23:45'))
        print(get_sec('0:04:15'))
        print(get_sec('0:00:25'))
        

        【讨论】:

          【解决方案9】:

          我不太喜欢给出的任何答案,所以我使用了以下答案:

          def timestamp_to_seconds(t):
              return sum(float(n) * m for n,
                         m in zip(reversed(time.split(':')), (1, 60, 3600))
                         )
          

          【讨论】:

            【解决方案10】:

            使用日期时间模块

            import datetime
            t = '10:15:30'
            h,m,s = t.split(':')
            print(int(datetime.timedelta(hours=int(h),minutes=int(m),seconds=int(s)).total_seconds()))
            

            输出:36930

            【讨论】:

            • 给定 OP 的示例输入,您的代码输出是什么样的?
            • 您不需要re。字符串有一个拆分方法:str.split()。使用 t.split(':') 而不是 re.split(':', t) 会更干净。
            • 我最终使用了这个解决方案,因为它似乎是最标准的做法。我使用理解列表稍微改变了 h,m,s 到 int 的转换,以使转换行更清晰,最终看起来像这样:h, m, s = [int(x) for x in t.split(':')]
            【解决方案11】:

            您可以将时间拆分为一个列表并添加每个单独的时间分量,将小时分量乘以 3600(一小时的秒数)和分钟分量乘以 60(一分钟的秒数),例如:

            timeInterval ='00:35:01'
            list = timeInterval.split(':')
            hours = list[0]
            minutes = list[1]
            seconds = list[2]
            total = (int(hours) * 3600 + int(minutes) * 60 + int(seconds))
            print("total = ", total)
            

            【讨论】:

              【解决方案12】:

              您可以使用 lambda 并减少列表以及 m=60s 和 h=60m 的事实。 (请参阅http://www.python-course.eu/lambda.php 上的“减少列表”)

              timestamp = "1:23:45"
              seconds = reduce(lambda x, y: x*60+y, [int(i) for i in (timestamp.replace(':',',')).split(',')])
              

              【讨论】:

                【解决方案13】:

                如果你有几天的字符串,另一种选择:

                def duration2sec(string):
                    if "days" in string:
                        days = string.split()[0]
                        hours = string.split()[2].split(':')
                        return int(days) * 86400 + int(hours[0]) * 3600 + int(hours[1]) * 60 + int(hours[2])
                    else:
                        hours = string.split(':')
                        return int(hours[0]) * 3600 + int(hours[1]) * 60 + int(hours[2])
                

                【讨论】:

                • 问题要求将 H:MM:SS 时间字符串转换为秒而不是将天转换为秒。请尝试改写您对该问题的答案
                • 这个例子是功能性的,else 部分会做到这一点。但我同意越简单越好。
                【解决方案14】:
                parts = time_string.split(":")
                seconds = int(parts[0])*(60*60) + int(parts[1])*60 + int(parts[2])
                

                【讨论】:

                • 几乎工作了,我不得不使用 int(...) 作为 taskinoor 建议的它才能正常工作。
                猜你喜欢
                • 2020-04-24
                • 2012-05-26
                • 2016-10-02
                • 2011-07-04
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-11-27
                • 1970-01-01
                相关资源
                最近更新 更多