pythonpython-2.7python-3.xjsonpickle

jsonpickle datetime to readable json format


Is it possible to convert datetime into a readable JSON format (which could be used from javascript)? Currently jsonpickle provides only a binary encoded value for datetime.


Solution

  • After some trial and error I came up with the following solution:

    class DatetimeHandler(jsonpickle.handlers.BaseHandler):
        def flatten(self, obj, data):
            return obj.strftime('%Y-%m-%d %H:%M:%S.%f')
    
    jsonpickle.handlers.registry.register(datetime, DatetimeHandler)
    
    encoded_datetime = jsonpickle.encode(datetime.now())
    print(encoded_datetime)
    decode_datetime = jsonpickle.decode(encoded_datetime)
    print(decode_datetime)