Home > Backend Development > Python Tutorial > How to Serialize Python datetime Objects in JSON?

How to Serialize Python datetime Objects in JSON?

DDD
Release: 2024-12-18 08:29:09
Original
290 people have browsed it

How to Serialize Python datetime Objects in JSON?

JSON Serialization of Datetime Objects

When attempting to convert a Python dictionary containing datetime objects to JSON using the jsonify() function, you may encounter the error "datetime.datetime not JSON serializable." This error occurs because JSON does not natively support datetime objects.

To resolve this issue and successfully serialize your dictionary, you can utilize the default parameter of the json.dumps() function, as demonstrated in the following example:

import json

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

# Convert the dictionary to JSON while handling datetime objects
json_data = json.dumps(sample, indent=4, sort_keys=True, default=str)
Copy after login

The default=str argument ensures that objects that are not inherently JSON serializable, such as datetime objects, are converted to strings. This allows the JSON serialization process to proceed successfully, resulting in a JSON string that you can further use or manipulate.

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

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template