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"

2 thoughts on “The “datetime.datetime not JSON serializable” thing”

  1. Matt,

    You can also coerce the datetime.datetime to a string to achieve the same result (without the ISO formatting). An added benefit is that it works with timedeltas, too.

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.