80

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 seconds

3.'00:01:04,000' -> 64 seconds

4.'01:01:09,000' -> 3669 seconds

Do I need to use regex to do this? I tried to use the time module, but

time.strptime('00:00:00,000','%I:%M:%S')

throws:

ValueError: time data '00:00:00,000' does not match format '%I:%M:%S'

Edit:

Looks like this:

from datetime import datetime
pt = datetime.strptime(timestring,'%H:%M:%S,%f')
total_seconds = pt.second + pt.minute*60 + pt.hour*3600

gives the correct result. I was just using the wrong module.

1
  • 4
    You don't need to use datatime.datetime.strptime, time.strptime works for that as well, it's just not in the documentation for some reason...
    – Josiah
    May 19, 2012 at 8:54

13 Answers 13

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

A little more pythonic way I think would be:

timestr = '00:04:23'

ftr = [3600,60,1]

sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])

Output is 263Sec.

I would be interested to see if anyone could simplify it further.

3
  • 2
    List comprehensions are more pythonic. So sum([a*b for a,b in zip(ftr, [int(i) for i in timestr.split(":")])]) would be more pythonic. Oct 5, 2012 at 4:57
  • 2
    Thanks Le Vieux Gildas.. it should be 263.. ftr should not have been [3600,60,0].. it must be [3600,60,1]... thanks agian Oct 12, 2012 at 6:44
  • you forgot to convert the string into an integer => lambda x : sum([int(x)*int(y) for x,y in zip([3600,60,1],x.split(":"))])
    – greendino
    Jan 14, 2021 at 19:02
34

without imports

time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":"))) 
2
  • 12
    Excellent answer, small adjustment to be able to handle both mm:ss and hh:mm:ss formats correctly just reverse the split.sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time.split(":")))) Mar 2, 2018 at 22:33
  • 1
    small adjustment to also handle fractions of a second (cast to float rather than int) sum(x * float(t) for x, t in zip([1, 60, 3600], reversed(time.split(":"))))
    – John
    Feb 3, 2022 at 22:13
13

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
8
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
1
  • 4
    adding an explanation is often helpful
    – con
    Feb 17, 2021 at 14:42
6

It looks like you're willing to strip fractions of a second... the problem is you can't use '00' as the hour with %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)
>>>
5

There is always parsing by hand

>>> 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
>>> 
1
  • 4
    I hate doing things by hand in Python :p
    – jamylak
    May 19, 2012 at 9:56
4
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())

result: 3.0

4

.total_seconds() seems to be straightforward.

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
2

Inspired by sverrir-sigmundarson's comment:

def time_to_sec(time_str):
    return sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time_str.split(":"))))
0
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

Dynamic solution for HH:MM:SS and MM:SS. If you want to handle a command, use split(',') divide by 1000 or something and then add.

_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]
0

Why not use 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)

One function, works on either 10,40, 09:12,40 or 02:08:14,59. If you use . instead of , for decimal sign it's even more simpler:

def str_to_seconds(t):
    reduce(lambda prev, next: prev * 60 + next, [float(x) for x in t.split(":")], 0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.