代码之家  ›  专栏  ›  技术社区  ›  HSchmale

使用strtime的Python解析-月-日-小时:分钟:秒-年时区-格式不匹配

  •  0
  • HSchmale  · 技术社区  · 7 年前

    我在用python(datetime.datetime.strtime)解析“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套接字方法 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'
    

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

    2 回复  |  直到 7 年前
        1
  •  1
  •   hchw    7 年前

    您需要翻转参数,即:

    import datetime
    datetime.datetime.strptime("Mar  3 03:00:04 2019 GMT", "%b  %d %H:%M:%S %Y %Z")
    
        2
  •  1
  •   Ramesh    7 年前
    datetime.datetime.strptime(date_string, format)
    

    确切语法应如上所述。改变论点的顺序是可行的。

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