Categories
Python Answers

How to fix the “datetime.datetime not JSON serializable” error in Python?

Spread the love

Sometimes, we’ve to fix the "datetime.datetime not JSON serializable" error in Python.

In this article, we’ll look at how to fix the "datetime.datetime not JSON serializable" error in Python.

How to fix the "datetime.datetime not JSON serializable" error in Python?

To fix the "datetime.datetime not JSON serializable" error in Python, we can use the json.dumps method.

For instance, we write:

from datetime import date, datetime
from json import dumps


def json_serial(obj):
    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError("Type %s not serializable" % type(obj))


s = dumps(datetime.now(), default=json_serial)
print(s)

We create the json_serial function to serialize the datetime object into a string.

In the function,. we call isinstance with obj and (datetime, date) to check if obj that we’re trying to serialize is a date or datetime object.

If it is, then we return obj.isoformat to return a date string.

Otherwise, we raise a TypeError.

Next, we call dumps with a datetime object and set default to json_serial to use json_serial to do the serialization.

Therefore s is "2021-10-20T00:13:35.533502".

Conclusion

To fix the "datetime.datetime not JSON serializable" error in Python, we can use the json.dumps method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *