首页 > 解决方案 > 使用 strptime 解析的 Python - 月日时:分:秒年时区 - 与格式不匹配

问题描述

我在使用 python (datetime.datetime.strptime) 解析“Mar 3 03:00:04 2019 GMT”时遇到问题。我无法弄清楚问题是什么。起初我以为是因为这一天不是零填充的,但根据我发现的文档,情况并非如此。

import datetime
datetime.datetime.strptime("%b  %d %H:%M:%S %Y %Z", "Mar  3 03:00:04 2019 GMT")

我尝试在格式字符串中删除和添加空格。我也尝试过没有时区说明符,但运气不好。我试图解析的格式来自 ssl socket method getpeercert

ValueError                                Traceback (most recent call last)
<ipython-input-14-a9f4aa24cc39> in <module>
----> 1 datetime.datetime.strptime("%b  %d %H:%M:%S %Y %Z", "Mar  3 03:00:04 2019 GMT")

/usr/lib/python3.7/_strptime.py in _strptime_datetime(cls, data_string, format)
    575     """Return a class cls instance based on the input string and the
    576     format string."""
--> 577     tt, fraction, gmtoff_fraction = _strptime(data_string, format)
    578     tzname, gmtoff = tt[-2:]
    579     args = tt[:6] + (fraction,)

/usr/lib/python3.7/_strptime.py in _strptime(data_string, format)
    357     if not found:
    358         raise ValueError("time data %r does not match format %r" %
--> 359                          (data_string, format))
    360     if len(data_string) != found.end():
    361         raise ValueError("unconverted data remains: %s" %

ValueError: time data '%b  %d %H:%M:%S %Y %Z' does not match format 'Mar  3 03:00:04 2019 GMT'

我应该使用什么正确的格式字符串?

标签: pythondatetimestrptime

解决方案


您需要翻转参数,即:

import datetime
datetime.datetime.strptime("Mar  3 03:00:04 2019 GMT", "%b  %d %H:%M:%S %Y %Z")

推荐阅读