Home > Backend Development > Python Tutorial > How Can I Handle 'datetime.datetime not JSON serializable' Errors in Python?

How Can I Handle 'datetime.datetime not JSON serializable' Errors in Python?

Linda Hamilton
Release: 2024-12-08 17:25:11
Original
1071 people have browsed it

How Can I Handle

JSON Serialization of Datetime Objects

Encountering the "datetime.datetime not JSON serializable" error while attempting to jsonify dictionaries containing datetime objects highlights the need to address the JSON serialization limitations of Python's datetime type. To address this problem effectively, the following solution is proposed:

A customizable JSON serialization approach allows for the conversion of non-serializable objects, such as datetime, into JSON-compatible formats. By utilizing the default parameter in json.dumps(), you can define a function that handles the conversion of datetime objects.

For instance, a simple default function that converts datetime objects to strings can be implemented as follows:

def convert_datetime(o):
    if isinstance(o, datetime):
        return str(o)
    return o
Copy after login

By passing this function as the default argument to json.dumps(), you can ensure that datetime objects are converted to strings and serialized successfully:

json.dumps(sample, indent=4, sort_keys=True, default=convert_datetime)
Copy after login

This approach provides a flexible and customizable solution for serializing complex data structures, including those containing datetime objects, into JSON format.

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

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template