Search code examples
pythonjsondatetimeunicodesimplejson

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!


Solution

  • 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.