How to convert a time string to seconds?

前端 未结 9 1856
轮回少年
轮回少年 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: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
    

提交回复
热议问题