Home >Backend Development >Python Tutorial >How to Solve the 'datetime.datetime is not JSON serializable' Error in Python?

How to Solve the 'datetime.datetime is not JSON serializable' Error in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 01:58:13519browse

How to Solve the

Overcoming "datetime.datetime not JSON serializable" Error

When serializing a Python dictionary containing a datetime object, such as in the example provided, an error may occur: TypeError: datetime.datetime is not JSON serializable.

Solution:

One approach to resolve this issue is to specify a custom default function while serializing the dictionary into JSON. This function will handle the conversion of non-serializable objects, such as datetime objects, into a JSON-compatible format.

import json

sample = {}
sample['title'] = "String"
sample['somedate'] = datetime.datetime(2012, 8, 8, 21, 46, 24, 862000)

def datetime_handler(x):
    if isinstance(x, datetime.datetime):
        return x.isoformat()
    raise TypeError("Unknown type")

json_string = json.dumps(sample, default=datetime_handler)

In this solution, the datetime_handler function is defined to convert datetime objects into a string representation using the isoformat() method. This string representation can then be handled appropriately during deserialization.

By providing a custom default function like this, you can successfully convert your dictionary containing datetime objects into a JSON-serializable format.

The above is the detailed content of How to Solve the 'datetime.datetime is not JSON serializable' Error in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn