是否有用于从自然语言解析日期和时间的 Python 库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1495487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any python library for parsing dates and times from a natural language?
提问by Vasil
What I'm looking for is something that can translate 'tomorrow at 6am' or 'next moday at noon' to the appropriate datetime objects.
我正在寻找的是可以将“明天早上 6 点”或“下周一中午”转换为适当的日期时间对象的东西。
回答by Alex Barrett
parsedatetime- Python module that is able to parse 'human readable' date/time expressions.
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]))
Output
输出
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
回答by PaulMcG
See what you think of this examplefrom the pyparsing wiki. It handles the following test cases:
从 pyparsing wiki 中了解您对这个示例的看法。它处理以下测试用例:
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