How to overcome “datetime.datetime not JSON serializable” in python?

For others who do not need or want to use the pymongo library for this.. you can achieve datetime JSON conversion easily with this small snippet:

def default(obj): """Default JSON serializer.""" import calendar, datetime if isinstance(obj, datetime.datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() millis = int( calendar.timegm(obj.timetuple()) * 1000 + obj.microsecond / 1000 ) return millis

Then use it like so:

import datetime, json print json.dumps(datetime.datetime.now(), default=default)

output: '1365091796124'


http://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable-in-python

你可能感兴趣的:(How to overcome “datetime.datetime not JSON serializable” in python?)