python - 如何将描述时间的字符串转换为秒?
问题描述
我正在尝试制作一个将时间字符串(来自用户)转换为秒的函数。
我想做的是让用户将时间输入为字符串,例如:
"one hour and forty five minutes"
然后将其分解为几秒钟。所以上面的输出将是
6300 seconds
解决方案
如果您想从头开始,那么其他答案很好。以下是您无需输入太多内容即可完成的操作:
您需要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
推荐阅读
- aem - 在 Slightly 的条件元素中包装标记?
- c# - 从打开的 DataReader 中返回一个新对象 - 好不好?
- java - 在 Java 中使用 Hibernate 加入嵌入式 ID 列
- python - libvips / pyvips 访问多通道 tiff (OME-Tiff) 的一小部分
- python - 在函数 2 中使用函数 1 创建的 pandas 数据框?
- visual-studio-code - VSCode + 远程 WSL 某些功能不起作用
- python - 如何使用 python 从网站上抓取段落?
- java - 多态性实现对子字段的强制通用更改
- deep-learning - 连体网络的线性变换
- css - 如何使用 Sass '@use' 命令包含和使用外部变量文件?