How to convert a string describing time into seconds?

Tags: , , ,



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

6300 seconds

Answer

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



Source: stackoverflow