Hassan Baig Hassan Baig - 1 year ago 54
Python Question

Serializing and deserializing datetimefield type object (Django app)

In a Django app of mine, I have a datetime object that I need to serialize and then deserialize. When I try it, I get the error:

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

My code to serialize and deserialize is:

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

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

What am I doing wrong and how do I get over the hump? Your guidance is greatly appreciated.

Answer Source

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

(adds a T as the date/time separator, and hard codes the utc offset string part)

will resolve your problem ... and I guess its reasonably safe ... personally I always go with

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

that pretty much always works and does not require me to hardcode the datestring you may need pip install python-dateutil