How to Fix "datetime is not JSON serializable" TypeError in Python


Serializing a Python data structure as JSON is quite simple using json.dumps().

import json
d = {
  'dog': 'corgi'
}
print(json.dumps(d))
# {"dog": "corgi"}

Issue with datetime Serialization

However, what if we try to serialize a datetime object?

import json
import datetime
d = {
  'dog': 'corgi',
  'date': datetime.datetime.now()
}
print(json.dumps(d))
# TypeError: datetime.datetime(2020, 19, 8, 9, 1, 1, 100000) is not JSON serializable

Solution

We can use the default parameter in json.dumps() that will be called whenever it doesn’t know how to convert a value, like a datetime object.

We can write a converter function that stringifies our datetime object.

def defaultconverter(o):
  if isinstance(o, datetime.datetime):
      return o.__str__()

Any object that requires special conversions can be added inside if statements in our defaultconverter method.

We can then pass this function into that default parameter.

import json
import datetime
d = {
  'dog': 'corgi',
  'date': datetime.datetime.now()
}
print(json.dumps(d, default = defaultconverter))
# {"date": "2020-19-08 09:01:01.100000", "dog": "corgi"}