How to convert a time string to seconds?

前端 未结 9 1850
轮回少年
轮回少年 2020-11-30 00:44

I need to convert time value strings given in the following format to seconds, for example:

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

2.\'00:00:10,000\' -> 10 s         


        
相关标签:
9条回答
  • 2020-11-30 01:10

    For 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
    
    0 讨论(0)
  • 2020-11-30 01: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
    
    0 讨论(0)
  • 2020-11-30 01:12

    To get the timedelta(), you should subtract 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 above implies the input is less than a day, to support the time difference more than a day:

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

    To emulate .total_seconds() on Python 2.6:

    >>> from __future__ import division
    >>> ((td.days * 86400 + td.seconds) * 10**6 + td.microseconds) / 10**6
    111669.0
    
    0 讨论(0)
提交回复
热议问题