Python strptime ValueError:时间数据与格式不匹配 [英] Python strptime ValueError: time data does not match format

查看:315
本文介绍了Python strptime ValueError:时间数据与格式不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已在我的postgreSQL数据库中的datetime列中添加了时区。

I have added timezones to my datetime column in my postgreSQL DB.

现在,每次要比较日期时,我都会遇到上述错误。
在某些点上,我有JSON请求,datetime对象作为字符串传递,因此我需要解析它们,并获得以下附加时区信息:

Now I have the error above everytime I want to compare dates. On some points I have JSON requests, datetime objects are passed as strings, so I need to parse them, with the additonal timezone info I get:

ValueError: time data '2018-05-02 11:52:26.108540+02:00' 
does not match format '%Y-%m-%d %H:%M:%S.%f+%Z' 

我以前有过:

2018-05-02 11:52:26.108540

与以下命令完美配合:

%Y-%m-%d %H:%M:%S.%f

已添加的新信息是: +02: 00

strptime文档告诉我使用%z %Z ,但不起作用。

In the strptime docu it is telling me to use %z or %Z but it does not work.

编辑:

我正在使用Python 3

I am using Python 3

推荐答案

问题是偏移量 +02:00 您需要删除冒号':'然后它将起作用:

The issue is the offset +02:00 you need to remove the colon ':' then it will work:

In[48]:
dt.datetime.strptime('2018-05-02 11:52:26.108540+0200', '%Y-%m-%d %H:%M:%S.%f%z')

Out[48]: datetime.datetime(2018, 5, 2, 11, 52, 26, 108540, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

所以您需要遍历所有日期时间字符串并将其删除命令 strptime 正确解析

So you would need to go through all your datetime strings and remove this in order for strptime to parse it correctly

这篇关于Python strptime ValueError:时间数据与格式不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆