"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Serialize Python datetime Objects in JSON?

How to Serialize Python datetime Objects in JSON?

Published on 2024-12-22
Browse:808

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)

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3