I’m trying to make a function to convert a time string (from the user) to seconds.
what I would like to do is to let the user input the time as a string, like:
"one hour and forty five minutes"
and then break it down into seconds. So the output from the above will be
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]+['zero']+[time] elif not('second' in s): time = time+['zero'] time = [w2n.word_to_num(x) for x in time] out = time*3600+time*60+time return str(out)+' seconds'
>>> print(strTimeToSec('one hour and forty five minute'))
>>> print(strTimeToSec('one hour forty five minute and thirty three seconds'))