The “datetime.datetime not JSON serializable” thing

I hit this every time I start a new project involving APIs and data stored in PostgreSQL; and every time I spend ages googling to try and remember how to fix it.

The issue is that psycopg2 returns datetime.datetime types from database timestamp fields, which then can’t be converted when calling jsonify() on the returned dictionary.

There are actually quite a few ways to solve this and I’ve tended to use whichever one seems to hurt my head the least at the time…

Previously I’ve used the following method:

class DateEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.date):
return obj.isoformat()
return JSONEncoder.default(self, obj)

But this time I discovered it can actually be as simple as:

json_friendly_date = meany_datetime_type.isoformat()

.isoformat() returns you a nice ISO8601 complaint string which will then jsonify() nicely

>> datetime.datetime(2015, 11, 9, 20, 30, 00).isoformat()
"2015-11-09T20:30:00"