Basically I have the inverse of this problem: Python Time Seconds to h:m:s
I have a string in the format H:MM:SS (always 2 digits for minutes and seconds), and I nee
Using datetime module
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()))
Output: 36930
parts = time_string.split(":")
seconds = int(parts[0])*(60*60) + int(parts[1])*60 + int(parts[2])
I didn't really like any of the given answers, so I used the following:
def timestamp_to_seconds(t):
return sum(float(n) * m for n,
m in zip(reversed(time.split(':')), (1, 60, 3600))
)
ts = '1:23:45'
secs = sum(int(x) * 60 ** i for i, x in enumerate(reversed(ts.split(':'))))
print(secs)
Expanding on @FMc's solution which embodies half of Horner's method. Advantage of Horner's method: Skip reversing the list, avoid power calculation.
from functools import reduce
timestamp = "1:23:45"
reduce(lambda sum, d: sum * 60 + int(d), timestamp.split(":"), 0)
Another alternative if you have days on string:
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])