Python Time conversion h:m:s to seconds

后端 未结 7 1101
青春惊慌失措
青春惊慌失措 2021-01-02 11:32

I am aware that with the timedelta function you can convert seconds to h:m:s using something like:

>> import datetime
>> str(datetime.timedelta(s         


        
相关标签:
7条回答
  • 2021-01-02 11:44
    >>> import time, datetime
    >>> a = time.strptime("00:11:06", "%H:%M:%S")
    >>> datetime.timedelta(hours=a.tm_hour, minutes=a.tm_min, seconds=a.tm_sec).seconds
    666
    

    And here's a cheeky one liner if you're really intent on splitting over ":"

    >>> s = "00:11:06"
    >>> sum(int(i) * 60**index for index, i in enumerate(s.split(":")[::-1]))
    666
    
    0 讨论(0)
  • 2021-01-02 11:50
    >>> def tt(a):
    ...     b = a.split(':')
    ...     return int(b[0]) * 3600 + int(b[1]) * 60 + int(b[2])
    ... 
    >>> print tt('0:11:06')
    

    666

    0 讨论(0)
  • 2021-01-02 11:51

    This works in 2.6.4:

    hours, minutes, seconds = [int(_) for _ in thestring.split(':')]
    

    If you want to turn it back into a timedelta:

    thetimedelta = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)
    
    0 讨论(0)
  • 2021-01-02 11:52

    You don't need to import anything!

    def time(s):
      m = s // 60
      h = (m // 60) % 60
      m %= 60
      s %= 60
      return h,m,s
    
    0 讨论(0)
  • 2021-01-02 11:57

    Unfortunately, it's not as trivial as constructing a datetime object from a string using datetime.strptime. This question has been asked previously on Stack Overflow here: How to construct a timedelta object from a simple string , where the solution involved using python-dateutil.

    Alternatively, if you don't want to have to add another module, here is a class you can use to parse a timedelta from a string: http://kbyanc.blogspot.ca/2007/08/python-reconstructing-timedeltas-from.html

    0 讨论(0)
  • 2021-01-02 12:01
    def hms_to_seconds(t):
        h, m, s = [int(i) for i in t.split(':')]
        return 3600*h + 60*m + s
    
    0 讨论(0)
提交回复
热议问题