W3docs

How to overcome "datetime.datetime not JSON serializable"?

One way to overcome "datetime.datetime not JSON serializable" in Python is to use the json.dumps() method with the default argument, default=str, which converts the datetime object to a string before serializing.

One way to overcome "datetime.datetime not JSON serializable" in Python is to use the json.dumps() method with the default argument, default=str, which converts the datetime object to a string before serializing. Another way is to convert the datetime object to a JSON-serializable format like a string using isoformat().

Here is an example:

JSON serialize a datetime in Python

import json
from datetime import datetime

# Create a datetime object
now = datetime.now()

# Serialize the object to a JSON formatted string
json_str = json.dumps(now, default=str)

print(json_str)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use a custom JSON encoder class to handle datetime objects automatically during serialization.

JSON serialize a datetime in Python using a custom encoder

import json
from datetime import datetime, date

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

data = {'date': datetime.now()}
json.dumps(data, cls=DateTimeEncoder)