首页 > 解决方案 > 如何将描述时间的字符串转换为秒?

问题描述

我正在尝试制作一个将时间字符串(来自用户)转换为秒的函数。

我想做的是让用户将时间输入为字符串,例如:

"one hour and forty five minutes" 

然后将其分解为几秒钟。所以上面的输出将是

6300 seconds

标签: pythonstringdata-conversionseconds

解决方案


如果您想从头开始,那么其他答案很好。以下是您无需输入太多内容即可完成的操作:

您需要word2number为此解决方案安装。

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


推荐阅读