【问题标题】:Error converting string to date: does not match format '%b %d %Y %I:%M%p'将字符串转换为日期时出错:与格式 '%b %d %Y %I:%M%p' 不匹配
【发布时间】:2017-09-23 20:59:23
【问题描述】:

我有一个字符串格式的日期:“Wed, 26 Apr 2017 12:39:28 GMT”,需要转换为日期时间。

我使用 datetime.strptime 进行转换

例如:

datetime.strptime ("Wed, 26 Apr 2017 12:39:28 GMT", '% b% d% Y% I:% M% p')

但是,错误: ValueError: 时间数据 'Wed, 26 Apr 2017 12:39:57 GMT' 与格式 '% b% d% Y% I:% M% p' 不匹配

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    如果字符串不能按照格式解析,或者解析后有多余的数据,则抛出ValueError。您应该删除多余的空格并修改用于解析给定字符串的指令。

    你可以试试这个:

    >>> from datetime import datetime
    >>>
    >>> ds="Wed, 26 Apr 2017 12:39:28 GMT"
    >>>
    >>> datetime.strptime (ds, '%a, %d %b %Y %H:%M:%S %Z')
    datetime.datetime(2017, 4, 26, 12, 39, 28)
    

    更多详情来自strftime() and strptime() Behavior

    【讨论】:

      【解决方案2】:

      正如错误所说,字符串与格式不匹配。试试这个:

      datetime.datetime.strptime('Wed, 26 Apr 2017 12:39:28 GMT', '%a, %d %b %Y %H:%M:%S %Z')
      

      【讨论】:

        猜你喜欢
        • 2021-12-22
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 2021-03-09
        • 1970-01-01
        • 2013-09-09
        • 2021-02-26
        相关资源
        最近更新 更多