【问题标题】:Converting date format in apache logs to ISO format In Python 3在 Python 3 中将 apache 日志中的日期格式转换为 ISO 格式
【发布时间】:2019-02-06 23:51:22
【问题描述】:

我一直在尝试将 apache 日志中的日期格式转换为 Python 3 中的 ISO 格式,但我似乎无法让它工作。

如果我只包含天、月和年,而不是小时、分钟和秒,我可以让它工作。

Text = "25/Jan/2000:14:00:01"
Date = dateutil.parser.parse(Text)
Date = Date.isoformat()
print(Date)

# I receive the following error messages below

 Traceback (most recent call last):
  File "Z:/Test.py", line 3, in <module>
    Date = dateutil.parser.parse(Text)
  File "Z:\Python\lib\site-packages\dateutil\parser\_parser.py", line 1356, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "Z:\Python\lib\site-packages\dateutil\parser\_parser.py", line 648, in parse
    raise ValueError("Unknown string format:", timestr)
ValueError: ('Unknown string format:', '25/Jan/2000:14:00:01'

我也尝试过使用 datetime 模块 (datetime.datetime.strftime()) 但出现了同样的问题。

有人可以帮帮我吗?

【问题讨论】:

    标签: python-3.x python-datetime python-dateutil


    【解决方案1】:

    这是因为 parse() 方法期望日期的字符串格式为以下形式:25/Jan/2000 14:00:01。您需要用空格替换年份后的:。 做这样的事情会起作用:

    Text = "25/Jan/2000:14:00:01"             
    Date = parse(Text.replace(":", " ", 1))   
    Date = Date.isoformat()                   
    print(Date)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-01
      • 2023-03-31
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      • 2022-01-13
      相关资源
      最近更新 更多