【发布时间】:2015-03-05 13:13:59
【问题描述】:
PHP 有惊人的 strtotime() 函数,它几乎可以将任何东西转换为时间。
我在 Python 中寻找类似的东西?
举个例子说明原因:我正在解析具有最愚蠢格式的系统日志(又名rfc3164),其中省略了一年并包括一个以空格填充的月份。
目前在 Python 中我正在这样做:
import datetime
d='Mar 5 09:10:11' # as an example
# first remove the space, if it exists
if d[4] == ' ':
d = d[0:4] + d[5:]
# append this year (I know, it could be last year around Dec/Jan!)
d = str(datetime.datetime.now().year) + ' ' + d
# now we can feed it strptime
date = datetime.strptime(d, "%Y %b %d %H:%M:%S")
这真的很丑。
有没有更好的办法?
【问题讨论】:
标签: python date-parsing