Hassan Baig
Hassan Baig

Reputation: 15824

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.

Upvotes: 0

Views: 1489

Answers (2)

chucksmash
chucksmash

Reputation: 5997

So there are two things going on here:

  1. Your format string has a space between %d and %H but the test string has a T.

  2. Python's datetime.datetime.strptime does not work with timezone names/offsets. From the 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])).

So you can extract year, month, day, hour, minute, second and microsecond but the %z directive is for strftime only, not strptime.

So, in summary:

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)

but

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'

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113978

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

Upvotes: 2

Related Questions