If you get the following error in Python:

TypeError: Object of type datetime is not JSON serializable

..then you can solve it by using this trick:

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

The default=str parameter tells json.dumps to call str() on any object it doesn’t know how to serialize. Since datetime objects have a sensible string representation, this works well as a quick fix.

This commonly happens when you’re building an API response or logging data that includes datetime fields from a database query or ORM result. The json module only handles basic Python types (dict, list, str, int, float, bool, None) by default.

If you need more control over the format, you can write a custom encoder or convert datetimes to ISO format explicitly with .isoformat() before serializing.