【问题标题】:Parse common log date string with python用python解析常见的日志日期字符串
【发布时间】:2012-09-17 14:28:17
【问题描述】:

问题:

我即将在 Python 2.6 中解析一个日志文件。将common log 日期字符串解析为时间对象时出现问题:

13/Sep/2012:06:27:18 +0200

我已经尝试过的

使用dateutils.parser.parse

我已经尝试使用dateutils.parser.parse,但解析失败并出现以下错误:

ValueError: unknown string format

使用time.strptime

我尝试time.strptime 使用格式字符串%d/%b/%Y:%H:%M:%S %z,但在解析时区时遇到了麻烦:

ValueError: 'z' is a bad directive in format '%d/%b/%Y:%H:%M:%S %z'

有谁知道错误在哪里?还是只是错误的方法?

最终解决方案

最后我决定使用time.strptime 剥离时区信息:

time.strptime(datestring[:-6], '%d/%b/%Y:%H:%M:%S')

不想使用dateutils 的原因是dateutilsstrptime 慢得多(它实际上调用了一个C 函数)。

【问题讨论】:

    标签: python parsing datetime python-2.6


    【解决方案1】:

    这是我看到的:

    • dateutil 不喜欢在日期后面加上时间
    • 您的底层 C 实现不支持 %z 指令(请参阅 this question

    一个快速简单的解决方案(虽然,不是很优雅):

    >>> s = '13/Sep/2012:06:27:18 +0200'
    >>> dateutil.parser.parse(s.replace(':', ' ', 1))
    datetime.datetime(2012, 9, 13, 6, 27, 18, tzinfo=tzoffset(None, 7200))
    

    提醒一下,replace 的可选第三个参数是max replacement count

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 2011-07-21
      • 2012-06-14
      • 1970-01-01
      • 2017-11-21
      相关资源
      最近更新 更多