Home >Backend Development >Python Tutorial >How Do I Handle the 'datetime.datetime not JSON serializable' Error?

How Do I Handle the 'datetime.datetime not JSON serializable' Error?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 22:35:14304browse

How Do I Handle the

Addressing JSON Serialization Issues with datetime.datetime

When attempting to create a JSON string representation of a dictionary containing a datetime object, you may encounter the "datetime.datetime not JSON serializable" error. To resolve this, consider implementing the following solution:

Modify the JSON serialization process by specifying a default function that handles non-serializable objects. Here's an example:

import json

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

json_string = json.dumps(sample, indent=4, sort_keys=True, default=str)

In the above example, the default function "str" is used to convert the datetime object to a string. This ensures that the entire dictionary can be serialized into a valid JSON string.

The above is the detailed content of How Do I Handle the 'datetime.datetime not JSON serializable' Error?. 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