Have some nested objects that I’d like serialize using JSON. The problem is that some of the properties contain datetimes. When I try to serialize these pbjects, Python throws an exception:
TypeError: datetime.datetime(2012, 6, 5, 17, 49, 35, 672115) is not JSON serializable
Using Python 2.7, is there a way to tell the json serializer: “When you see a datetime, don’t be annoying and throw an exception, just serialize using: property.strftime('%Y-%m-%d %I:%M%p')“
Thanks!
You’ll want to define a helper function that will serialize
datetimeobjects, and usedefaultkwarg of json.dump or json.dumps. See the comments with links to the duplicate answers.Also, you will want to consider whether to support or not to support timezone-aware
datetimeobjects. And whether you want to preserve the timezone during the serialization or just convert to UTC prior to serialization.Here’s an example that assumes you want to convert to UTC before serialization. It relies upon python-dateutil library: