How to Convert an H:Mm:Ss Time String to Seconds in Python

How to convert an H:MM:SS time string to seconds in Python?

def get_sec(time_str):
"""Get seconds from time."""
h, m, s = time_str.split(':')
return int(h) * 3600 + int(m) * 60 + int(s)

print(get_sec('1:23:45'))
print(get_sec('0:04:15'))
print(get_sec('0:00:25'))

How to convert a time string to seconds?

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

How to convert a hh:mm:ss to seconds without a time_string in python?

You added unnecessary complication:
just do:

def to_seconds(hours, minutes, seconds):
return hours*3600 + minutes*60 + seconds

Your current error is:

hh = '(0,'
mm = '60,'
ss = '0)'

As you know we can't convert '(0,','60,' or '0)' to int.

Another converting hh:mm:ss to seconds

def getSec(s):
l = map(int, s.split(':')) # l = list(map(int, s.split(':'))) in Python 3.x
return sum(n * sec for n, sec in zip(l[::-1], (1, 60, 3600)))

getSec('20') # 20
getSec('1:20') # 80
getSec('1:30:01') # 5401

How to convert A hours and minutes and seconds string to HH:MM:SS format?

This returns total number of seconds, which seems to be what you wanted:

def parsex(s):
hh = mm = ss = 0
for word in s.split():
word = word.lower()
if word.isdigit():
save = word
elif word.startswith('hour'):
hh = int(save)
elif word.startswith('minute'):
mm = int(save)
elif word.startswith('second'):
ss = int(save)
return (hh*60+mm)*60+ss

print(parsex('1 hour and 30 seconds'))
print(parsex('2 hours 15 minutes 45 seconds'))

Convert time (HH:MM:SS) to minutes in python

You can use sum with a generator expression or map:

from operator import mul

my_time = '9715:56:46'
factors = (60, 1, 1/60)

t1 = sum(i*j for i, j in zip(map(int, my_time.split(':')), factors))
t2 = sum(map(mul, map(int, my_time.split(':')), factors))

print(t1) # 582956.7666666667

assert t1 == t2

How to convert HH:MM:SS to time.time() object in Python

To get UNIX time, you need to add a date. For example, you could combine your time string with today's date:

from datetime import datetime, timezone

s = '14:37:29'
today = datetime.today() # 2020-09-16

# make a datetime object with today's date
dt = datetime.combine(today, datetime.strptime(s, '%H:%M:%S').time())

# make sure it's in UTC (optional)
dt = dt.replace(tzinfo=timezone.utc)

# get the timestamp
ts = dt.timestamp()
print(ts)
# 1600267049.0

You could also set other time zones with this approach using dateutil or zoneinfo (Python 3.9+).

Convert HH:MM:SS string to seconds only in javascript

Try this:

var hms = '02:04:33';   // your input string
var a = hms.split(':'); // split it at the colons

// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);

console.log(seconds);

How to convert a string describing time into seconds?

If you want to do it from scratch then other answers are good. Here's what you can do without typing much:

You need to have word2number installed for this solution.

from word2number import w2n
import re
def strTimeToSec(s):
s = s.replace(' and', '')
time = re.split(' hour| hours| minute| minutes| second| seconds', s)[:-1]
if not('hour' in s):
time = ['zero']+time
elif not('minute' in s):
time = [time[0]]+['zero']+[time[1]]
elif not('second' in s):
time = time+['zero']
time = [w2n.word_to_num(x) for x in time]
out = time[0]*3600+time[1]*60+time[2]
return str(out)+' seconds'

>>> print(strTimeToSec('one hour and forty five minute'))

6300 seconds

>>> print(strTimeToSec('one hour forty five minute and thirty three seconds'))

6333 seconds

How do I convert seconds to hours, minutes and seconds?

You can use datetime.timedelta function:

>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'


Related Topics



Leave a reply



Submit