Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert simplejson dumped unicode datetime back to datetime object

I have...

entity = simplejson.dumps({"a":unicode(datetime.datetime.utcnow())})

How do I convert the datetime (that was converted to unicode) back to datetime again?

So that I can do something like...

entity2 = simplejson.loads(entity)
#your answer here..
add5 = entity2["a"] + datetime.timedelta(minutes=5)

Thanks!

like image 290
Albert Avatar asked Jan 19 '23 20:01

Albert


2 Answers

DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'

Do the following before serializing:

time = datetime.strftime(time, DATETIME_FORMAT)

Do the following after unserializing:

time = datetime.strptime(time, DATETIME_FORMAT)

example:

>>> from datetime import datetime

>>> DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'

>>> time = datetime.now()
>>> time
datetime.datetime(2011, 5, 5, 3, 1, 45, 646302)

>>> time = time.strftime(DATETIME_FORMAT)
>>> time
'2011-05-05 03:01:45'

>>> import json

>>> time = json.loads(json.dumps(time))
>>> time
'2011-05-05 03:01:45'

>>> time = datetime.strptime(time, DATETIME_FORMAT)
>>> time
datetime.datetime(2011, 5, 5, 3, 1, 45)

In case you find this somewhat inelegant, you might consider a custom json encoder/decoder. I personally have tried the ones in the default json package, but gave up pulling my hair out with cryptic error messages. If you go this path, I might recommend a third party json package.

like image 98
ninjagecko Avatar answered Jan 23 '23 07:01

ninjagecko


Use datetime.datetime.strptime.

dt = datetime.datetime.strptime(entity2['a'], '%Y-%m-%d %H:%M:%S.%f')
like image 37
zeekay Avatar answered Jan 23 '23 07:01

zeekay