2016-05-31 161 views
0

在我的Django应用程序中,我有一个需要序列化然后反序列化的日期时间对象。当我尝试它,我得到的错误:序列化和反序列化datetimefield类型对象(Django应用程序)

ValueError: time data '2016-05-31T18:57:17.280939+00:00' does not match format '%Y-%m-%d %H:%M:%S.%f'

我的代码序列化和反序列化是:

timestring = time.isoformat() #where timestring is DateTimeField type object, instantiated in Django 

timeobj = datetime.strptime(timestring, "%Y-%m-%d %H:%M:%S.%f") 

什么我做错了,我怎么渡过了难关?非常感谢您的指导。

+0

尝试使用'蟒蛇-dateutil','dateutil.parser.parse'具体...问题是日期时间不知道时区默认情况下(pytz可以帮助一点)..但+00:00是什么打破它... dateutil应该正确处理... –

+0

或者你可以'timeobj = datetime.strptime(timestring,“%Y - %m-%dT%H:%M:%S.%f + 00:00“)如果它总是+00:00 –

+0

@JoranBeasley:是的, ut(始终为+00:00),但仍会得到:'ValueError:时间数据'2016-05-31T19:10:26.083572 + 00:00'与格式不匹配'%Y-%m-%d%H: %M:%S.%f + 00:00'' –

回答

1

timeobj = datetime.strptime(timestring, "%Y-%m-%dT%H:%M:%S.%f+00:00")

(增加了T的日期/时间分隔符,和硬编码的UTC偏移量字符串部分)

能够解决您的问题...我猜其合理的安全...个人我总是

from dateutil.parser import parse as date_parse 
dt_obj = date_parse(timestring) 

是几乎总是工作,并不需要我硬编码datestring去,你可能需要pip install python-dateutil

0

因此,有两件事情怎么回事:

  1. 你的格式字符串具有%d%H之间的空间,但测试字符串有T

  2. Python的datetime.datetime.strptime不适用于时区名称/偏移量。从relevant docs

classmethod datetime.strptime(date_string, format) 

Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

所以,你可以提取yearmonthdayhourminutesecondmicrosecond%z指令是strftime只,而不是strptime

因此,简言之:

In [18]: datetime.strptime(datetime.today().isoformat(), '%Y-%m-%dT%H:%M:%S.%f') 
Out[18]: datetime.datetime(2016, 5, 31, 15, 20, 20, 581261) 

In [22]: datetime.strptime(datetime.today().isoformat()+'+00:00', '%Y-%m-%dT%H:%M:%S.%f%z') 
--------------------------------------------------------------------------- 
ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S.%f%z'