【问题标题】:Parse a Date in Python with datetime使用日期时间在 Python 中解析日期
【发布时间】:2019-03-06 22:59:32
【问题描述】:

我得到这个字符串:

a = "Wed Mar 06 2019 17:35:33 GMT-0500 (Ecuador Time)"

我正在尝试使用以下代码在 python 中解析它:

fecha = datetime.strptime(a , '%a %b %d %Y %H:%M:%S GMT%z (%Z)')

但是我遇到了一个错误

ValueError: time data 'Wed Mar 06 2019 17:35:33 GMT-0500 (Ecuador Time)' does not match format '%a %b %d %Y %H:%M:%S GMT%z (%Z)'

我做错了什么?我已经尝试了很多日期设置,但仍然可以获得解决方案我的目标是获取日期对象并将其保存到 MongoDatabase

【问题讨论】:

    标签: python string datetime parsing


    【解决方案1】:

    代码的问题是“(厄瓜多尔时间)”不是匹配“(%Z)”所需的格式。

    要修复您的代码,您只需从字符串中删除“(厄瓜多尔时间)”并删除“(%Z)”即可。由于您已经有了 GMT 偏移量,所以它应该没有太大关系。

    这将使您的代码为:

    from datetime import datetime
    
    a = "Wed Mar 06 2019 17:35:33 GMT-0500"
    fetcha = datetime.strptime(a , '%a %b %d %Y %H:%M:%S GMT%z')
    

    【讨论】:

    • 非常感谢这个工作我这样拆分字符串:texto = a.split()texto = texto[0]+" "+texto[1]+" "+texto[2]+" "+texto[3]+" "+texto[4]+" "+texto[5] 然后我可以解析它再次谢谢你:)
    • 我建议您先使用a = "Wed Mar 06 2019 17:35:33 GMT-0500 (Ecuador Time)",然后再使用a = a.split(' (')[0],但您的方式也应该可以。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2014-01-29
    • 2022-01-22
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多