Date problems converting a dictionary to JSON

If you want to convert a dictionary object to JSON you would use something like:

myJSON = json.dumps(myDict, indent=4, sort_keys=True)

So if we have a simple script that looks like:

This produces:

C:\Projects\Examples>python json_dump_std.py
{
    "fred": {
        "age": 20,
        "home_time": "21/12/2019 15:30",
        "lunch_time": "21/12/2019 13:00",
        "start_time": "21/12/2019 10:30"
    },
    "jim": {
        "age": 31,
        "home_time": "21/12/2019 17:30",
        "lunch_time": "21/12/2019 12:00",
        "start_time": "21/12/2019 08:30"
    }
}

But things get complicated when we use dates rather than strings:

Which instead produces:

C:\Projects\Examples>python json_dump.py
Traceback (most recent call last):
File "json_dump.py", line 22, in <module>
print(json.dumps(myDict, indent=4, sort_keys=True))
File "C:\Python\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Python\lib\json\encoder.py", line 201, in encode
chunks = list(chunks)
File "C:\Python\lib\json\encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "C:\Python\lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Python\lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Python\lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "C:\Python\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type datetime is not JSON serializable

Simple answer provided by jjmontes in a stackoverflow post:

https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable

Is to change it to: json.dumps(myDict, indent=4, sort_keys=True, default=str)

Thus giving:

Which gives the desired result:

{
    "fred": {
        "age": 20,
        "home_time": "2019-12-21 15:30:00",
        "lunch_time": "2019-12-21 13:00:00",
        "start_time": "2019-12-21 10:30:00"
    },
    "jim": {
        "age": 31,
        "home_time": "2019-12-21 17:30:00",
        "lunch_time": "2019-12-21 12:00:00",
        "start_time": "2019-12-21 08:30:00"
    }
}