Python: convert simplejson dumped unicode datetime back to datetime object

I have...

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

How can I convert date-time (converted to unicode) back to date-time again?

So I can do something like ...

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

Thanks!

+4
source share
2 answers
 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' 

Before serializing, do the following:

 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) 

If you find this to be somewhat inelegant, you might consider a custom json encoder / decoder. I personally tried the ones that were in the json package by default, but refused to stretch my hair with cryptic error messages. If you go this way, I can recommend a third-party json package.

+7
source

Use datetime.datetime.strptime .

 dt = datetime.datetime.strptime(entity2['a'], '%Y-%m-%d %H:%M:%S.%f') 
+2
source

All Articles