Python模糊时间戳解析

6 投票
3 回答
5580 浏览
提问于 2025-04-15 13:31

有没有一个Python模块可以像unix中的date命令那样理解模糊的时间戳呢?

> date -d "2 minutes ago"
Tue Aug 11 16:24:05 EST 2009

我找到的最接近的模块是dateutil.parser,但它对上面的例子不太管用。

谢谢

3 个回答

1

我最近在尝试用pyparsing这个工具来做一些事情,你可以在这里找到我最新的尝试。它在这些测试案例中运行得不错:

today
tomorrow
yesterday
in a couple of days
a couple of days from now
a couple of days from today
in a day
3 days ago
3 days from now
a day ago
now
10 minutes ago
10 minutes from now
in 10 minutes
in a minute
in a couple of minutes
20 seconds ago
in 30 seconds
20 seconds before noon
20 seconds before noon tomorrow
noon
midnight
noon tomorrow
2

dateparser

使用方法:

>>> import dateparser
>>> dateparser.parse('2 minutes ago')
datetime.datetime(2018, 11, 27, 13, 44, 54, 993170)
>>> dateparser.parse('yesterday at 15:12')
datetime.datetime(2018, 11, 26, 15, 12)
9

看看这个开源模块:parsedatetime

撰写回答