Why does json serialization of datetime objects in python not work out of the box for datetime objects Why does json serialization of datetime objects in python not work out of the box for datetime objects python python

Why does json serialization of datetime objects in python not work out of the box for datetime objects


No it doesn't work that way in json module. The module provides you with a default encoder: json.JSONEncoder. You need to extend this to provide your implementation of default method to serialize objects. Something like this:

import jsonimport datetimefrom time import mktimeclass MyEncoder(json.JSONEncoder):    def default(self, obj):        if isinstance(obj, datetime.datetime):            return int(mktime(obj.timetuple()))        return json.JSONEncoder.default(self, obj)print json.dumps(obj, cls=MyEncoder)

As others correctly pointed out, the reason is that the standard for json does not specify how date time can be represented.


How would you like them to be serialized?

JSON doesn't specify how to handle dates, so the python json library cannot make the decision on how to then represent these for you. That completely depends on how the other side (browser, script, whatever) handles dates in JSON as well.


A simple way to patch the json module such that serialization would support datetime.

import jsonimport datetimejson.JSONEncoder.default = lambda self,obj: (obj.isoformat() if isinstance(obj, datetime.datetime) else None)

Than use json serialization as you always do - this time with datetime being serialized as isoformat.

json.dumps({'created':datetime.datetime.now()})

Resulting in: '{"created": "2015-08-26T14:21:31.853855"}'

See more details and some words of caution at:StackOverflow: JSON datetime between Python and JavaScript