是否存在与datetime
集成并理解人性化日期规范格式的现有Python包,有点类似于/usr/bin/date
在GNU Linux
上的做法?
$ date -d 'today'
Thu May 28 14:01:15 XXX 2015
$ date -d 'tomorrow'
Fri May 29 14:01:23 XXX 2015
$ date -d 'this Sunday'
Sun May 31 00:00:00 XXX 2015
$ date -d 'Wednesday next week'
Wed Jun 10 00:00:00 XXX 2015
parsedatetime
可能有帮助:
import datetime as DT
import parsedatetime as pdt
p = pdt.Calendar()
for text in ('today', 'tomorrow', 'this Sunday', 'Wednesday next week', 'next week Wednesday', ):
timetuple, flag = p.parse(text)
date = DT.datetime(*timetuple[:6])
print('{:20} --> {}'.format(text, date))
收益率today --> 2015-05-28 09:00:00
tomorrow --> 2015-05-29 09:00:00
this Sunday --> 2015-05-31 09:13:46
Wednesday next week --> 2015-06-01 09:00:00
next week Wednesday --> 2015-06-03 09:00:00
但是注意Wednesday next week
被错误地解析了
python-dateutil是另一个PyPI库,用于模糊匹配和输入。
我个人使用delorean,它具有你提到的那种自然语言特征,例如:
>>> d.last_tuesday()
Delorean(datetime=2013-01-15 19:41:06.207481+00:00, timezone=UTC)