Home >Backend Development >Python Tutorial >How Do I Handle the 'datetime.datetime not JSON serializable' Error?
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!