Skip to main content
 首页 » 编程设计

python之在 Python 中解析任意日期格式(包括 rfc3164)

2025年05月04日13rubylouvre

<分区>

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") 

这真的很丑。

有没有更好的办法?