How to overcome "datetime.datetime not JSON serializable" in python?
Question: I have a basic dict as follows:

    
    
    sample = {}
    sample['title'] = "String"
    sample['somedate'] = somedatetimehere
    

When I try to do `jsonify(sample)` I get:

> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON
> serializable

What can I do such that my dictionary sample can overcome the error above?

Note: Though it may not be relevant, the dictionaries are generated from the
retrieval of records out of mongodb where when I print out
`str(sample['somedate'])`, the output is `2012-08-08 21:46:24.862000`.


Answer: Building on other answers, a simple solution based on a specific serializer
that just converts datetime.datetime objects to strings.

    
    
    from datetime import datetime
    
    def json_serial(obj):
        """JSON serializer for objects not serializable by default json code"""
    
        if isinstance(obj, datetime):
            serial = obj.isoformat()
            return serial
        raise TypeError ("Type not serializable")
    

As seen, the code just checks to find out if object is of class
datetime.datetime, and then uses .isoformat() to produce a serialized version
of it, according to ISO 8601 format, YYYY-MM-DDTHH:MM:SS (which is easily
decoded by JavaScript). If more complex serialized representations are sought,
other code could be used instead of str() (see other answers to this question
for examples). The code ends by raising an exception, to deal with the case it
is called with a non-serializable type which is not datetime.

This json_serial function can be used as follows:

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

The details about how the default parameter to json.dumps works can be found
in [Section Basic Usage of the json module
documentation](http://docs.python.org/2/library/json.html#basic-usage).

