【问题标题】:Parse arbitary date formats in Python (including rfc3164) [duplicate]在 Python 中解析任意日期格式(包括 rfc3164)[重复]
【发布时间】: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


    【解决方案1】:

    我认为您正在寻找dateutils 模块:

    In [12]: d = 'Mar  5 09:10:11'
    
    In [13]: import dateutil
    
    In [14]: dateutil.parser.parse(d)
    Out[14]: datetime.datetime(2015, 3, 5, 9, 10, 11)
    

    【讨论】:

    • 令人惊讶的 Python 没有这个核心。不过谢谢,这正是我所需要的。
    • @artfulrobot 如果有帮助,别忘了接受它:)
    • 是的,谢谢,这是愚蠢的“哦,你不能在 36.4 秒内接受这个答案”这件事让我忘记了。有一天必须在元上询问这些限制的目的是什么!
    猜你喜欢
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2013-06-03
    • 2013-09-18
    • 1970-01-01
    • 2015-01-11
    相关资源
    最近更新 更多