本文介绍了如何解析 Python 中的自由文本时间间隔,范围从几年到几秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 Python 解析如下所示的自由文本时间间隔:
I would like to parse free-text time intervals like the following, using Python:
- 1 秒
- 2 分钟
- 3 小时
- 4 天
- 5 周
- 6 个月
- 7 年
有没有一种轻松的方法来做到这一点,最好是简单地调用一个库函数?
Is there a painless way to do this, ideally by simply calling a library function?
我试过了:
dateutil.parser.parse()
,它可以理解秒到小时,但不能理解为几天或更长时间.mx.DateTime.DateTimeDeltaFrom()
,它可以理解几天但几周或更长时间失败,并且是静默的(例如,它可能会创建长度为 0 的间隔,或将2 个月"解析为2 分钟).
dateutil.parser.parse()
, which understands seconds through hours but not days or more.mx.DateTime.DateTimeDeltaFrom()
, which understands through days but fails on weeks or higher, and silently (e.g., it might create an interval of length 0, or parse "2 months" as 2 minutes).
推荐答案
这个对我来说是新的,但是基于一些谷歌搜索,你是否尝试过 呜呜?
This one is new to me, but based on some googling have you tried whoosh?
还有 parsedatetime:
#!/usr/bin/env python
from datetime import datetime
import parsedatetime as pdt # $ pip install parsedatetime
cal = pdt.Calendar()
for time_str in ['1 second', '2 minutes','3 hours','5 weeks','6 months','7 years']:
diff = cal.parseDT(time_str, sourceTime=datetime.min)[0] - datetime.min
print("{time_str:<10} -> {diff!s:>20} <{diff!r}>".format(**vars()))
输出
1 second -> 0:00:01 <datetime.timedelta(0, 1)>
2 minutes -> 0:02:00 <datetime.timedelta(0, 120)>
3 hours -> 3:00:00 <datetime.timedelta(0, 10800)>
5 weeks -> 35 days, 0:00:00 <datetime.timedelta(35)>
6 months -> 181 days, 0:00:00 <datetime.timedelta(181)>
7 years -> 2556 days, 0:00:00 <datetime.timedelta(2556)>
这篇关于如何解析 Python 中的自由文本时间间隔,范围从几年到几秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!