将英语文本日期表达式解析为datetime

时间:2013-12-14 19:04:07

标签: python

如何转换这些字符串:

one hour ago
three days ago
two weeks ago
yesterday
next month

进入Python datetime对象?

1 个答案:

答案 0 :(得分:0)

刚刚找到parsedatetime,用于解析Jon Clements提供的link中的人类可读日期/时间文本。如果您感兴趣,这是一个解决方案:

from time import mktime
from datetime import datetime
import parsedatetime as pdt

time_str = '1 hour ago'
cal = pdt.Calendar()
dt = datetime.fromtimestamp(mktime(cal.parse(time_str)[0]))
time_formatted = dt.strftime('%b %d, %Y %H:%M')
print(time_formatted) # will print something like: Dec 15, 2013 02:10

另请参阅此问题:python 'x days ago' to datetime