A demo in the official documentation:
>>> Import json>>> class Complexencoder (JSON. Jsonencoder): ... def default (self, obj): ... If Isinstance (obj, complex): ... return [Obj.real, Obj.imag] ... Return JSON. Jsonencoder.default (self, obj) ...>>> dumps (2 + 1j, Cls=complexencoder) ' [2.0, 1.0] ' >>> Complexencoder (). Encode (2 + 1j) ' [2.0, 1.0] ' >>> list (Complexencoder (). Iterencode (2 + 1j)) [' [', ' 2.0 ', ', ', ' 1.0 ‘, ‘]‘]
Then simply extend a jsonencoder out to format the time
Class Cjsonencoder (JSON. Jsonencoder): def default (self, obj): if Isinstance (obj, datetime): return Obj.strftime ('%y-%m-%d%h:%m: %s ') elif isinstance (obj, date): return obj.strftime ('%y-%m-%d ') else: return JSON. Jsonencoder.default (self, obj)
When using, simply add a CLS parameter to the Json.dumps:
Json.dumps (DataList, Cls=cjsonencoder)
If you do not want to define a class, you can format it directly after the date or DateTime object we get, using the Strftime method.
Solve Python's own JSON does not serialize Data,datetime type data problems