E-mail : support@tech2now.in

How to Fix – “datetime.datetime not JSON serializable” in Python?

We can fix this error by following way.

import json
import datetime

data = {
    "id": 123,
    "name": "Anupam Kumar Dwivedi",
    "saley": 11000,
    "updated": datetime.datetime.now()
}

def default(obj):
    if isinstance(obj, (datetime.date, datetime.datetime)):
        return obj.isoformat()

print("JSON Data")
print(json.dumps(data, default=default))
Output:
JSON Data
{"id": 123, "name": "Anupam Kumar Dwivedi", "saley": 11000, "updated": "2023-09-10T14:40:56.269068"}

GitHub Repository URL