python 自定义 JSON Encoder
继承 json.JSONEncoder 类, 重载 default 方法
1 2 3 4 5 6 7 8 9 10 11
| def convert_time(dt: DateTime): pdt = datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, int(dt.second), int(dt.second * 1000000 % 1000000)) return pdt
class CustomJSONEncoder(JSONEncoder): def default(self, o): if isinstance(o, DateTime): return super(CustomJSONEncoder, self).encode(convert_time(o).isoformat()) return super(CustomJSONEncoder, self).default(o)
|