如何将自然语言中的日期和时间转换为日期时间?

36 投票
2 回答
18865 浏览
提问于 2025-04-15 14:41

我想找到一种方法,把“明天早上6点”或者“下周一中午”这样的说法转换成合适的日期时间对象。

我曾考虑过制定一套复杂的规则,但有没有其他更简单的方法呢?

2 个回答

11

看看你觉得这个来自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
6am tomorrow
0800 yesterday
12:15 AM today
3pm 2 days from today
a week from today
a week from now
3 weeks ago
noon next Sunday
noon Sunday
noon last Sunday
53

parsedatetime - 这是一个Python模块,可以解析人们常用的日期和时间表达方式。

#!/usr/bin/env python
from datetime import datetime
import parsedatetime as pdt # $ pip install parsedatetime

cal = pdt.Calendar()
now = datetime.now()
print("now: %s" % now)
for time_string in ["tomorrow at 6am", "next moday at noon", 
                    "2 min ago", "3 weeks ago", "1 month ago"]:
   print("%s:\t%s" % (time_string, cal.parseDT(time_string, now)[0]))

输出

now: 2015-10-18 13:55:29.732131
tomorrow at 6am:    2015-10-19 06:00:00
next moday at noon: 2015-10-18 12:00:00
2 min ago:  2015-10-18 13:53:29
3 weeks ago:    2015-09-27 13:55:29
1 month ago:    2015-09-18 13:55:29

撰写回答