How to Solve Python TypeError: Object of type datetime is not JSON serializable

by | Programming, Python, Tips

This error occurs when you try to serialize a datetime.datetime object to a JSON string using the json.dumps() method. You can solve this error by setting the default keyword argument to str when calling the json.dumps() method. For example,

json_str = json.dumps(sample_dict, default=str)

You can also define a function that converts the datetime to an isoformat string and set the default keyword argument to the function name.

This tutorial will go through how to solve the error with code examples.


TypeError: Object of type datetime is not JSON serializable

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part “Object of type datetime” tells us the error is due to an illegal operation with a datetime object.

Serialization in Python refers to converting a Python object into a transmittable format that we can recreate when needed using deserialization. JSON serialization returns a human-readable string form called a JSON string. The JSON encoder json.dump() and json.dumps() can only serialize certain object types like dictionaries, lists, or strings.

is not JSON serializable” informs us that the JSON serialization is an illegal operation for the datetime type.

Example

Let’s look at an example of JSON serializing a dictionary with the current date and time. First, we will import the datetime class and then call the now() method to get the current date and time.

from datetime import datetime
now = datetime.now()

Next, we will create a dictionary where the key is 'entry_created_at' and the value is the now variable. We will then attempt to serialize the dictionary using json.dumps().

sample_time = {'entry_created_at': now}
json_str = json.dumps(sample_time)

Let’s run the code to see what happens:

TypeError: Object of type datetime is not JSON serializable

The error occurs because the now variable is of type datetime and cannot be serialized into a JSON string.

Solution #1: Set default to str

The simplest way to solve this error is to set the default keyword argument to the str class. The default value for the keyword argument default is None. We can set default to a function that gets called for objects that are not serializable. When we set the default keyword argument to str , it converts the datetime object to a string.

Let’s look at the updated code:

sample_time = {'entry_created_at': now}
json_str = json.dumps(sample_time, default=str)
print(json_str)

Let’s run the code to see the JSON string.

{"entry_created_at": "2022-06-04 18:09:00.670426"}

Solution #2: Define a custom function to convert datetime to isoformat string

We can also solve this error by defining a custom function that converts datetime.datetime and datetime.date objects to ISO formatted strings using the datetime.datetime.isoformat() or datetime.date.isoformat() methods respectively. ISO formatted strings are JSON serializable. Let’s look at the custom function:

from datetime import datetime, date
import json
def datetime_to_isoformat(obj):
    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError ("Type %s is not serializable" % type(obj))

Note that if the object obj is not an instance of datetime or date the function will raise a TypeError. Let’s set the default keyword argument to our custom function and run the code:

json_str = json.dumps(sample_time, default=datetime_to_isoformat)
print(json_str)
{"entry_created_at": "2022-06-04T18:09:00.670426"}

Solution #3: Define a JSONEncoder subclass for the cls kwarg

We can also solve this error by building a custom JSONEncoder subclass. This subclass will override the default method to serialize additional types.

from datetime import datetime, date
import json
class datetime_encoder(json.JSONEncoder):
    def default(self, obj):

        if isinstance(obj, (datetime, date)):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

We have to specify the custom JSONEncoder subclass with the cls keyword argument. Otherwise, JSONEncoder is used.

json_str = json.dumps(sample_time, cls=datetime_encoder)
print(json_str)

Let’s run the code to see the result.

{"entry_created_at": "2022-06-04 18:09:00.670426"}

Below is the collection of objects that the JSONEncoder class supports and their JSON equivalent

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int- & float- derived Enumsnumber
Truetrue
Falsefalse
Nonenull
JSONEncoder Supported objects and types by default

Summary

Congratulations on reading to the end of this tutorial.

For further reading on errors involving JSON, go to the articles:

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!

Follow the Research Scientist Pod on Social media!