Python JSON encoder to support datetime?

后端 未结 9 1915
长发绾君心
长发绾君心 2020-12-03 10:24

is there any elegant way to make Python JSON encoder support datetime? some 3rd party module or easy hack?

I am using tornado\'s database wrapper to fetch some rows

9条回答
  •  半阙折子戏
    2020-12-03 11:03

    Create a custom decoder/encoder:

    class CustomJSONEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, datetime.datetime):
                return http_date(obj)
            if isinstance(obj, uuid.UUID):
                return str(obj)
            return json.JSONEncoder.default(self, obj)
    
    class CustomJSONDecoder(json.JSONDecoder):
        def __init__(self, *args, **kwargs):
            json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
    
        def object_hook(self, source):
            for k, v in source.items():
                if isinstance(v, str):
                    try:
                        source[k] = datetime.datetime.strptime(str(v), '%a, %d %b %Y %H:%M:%S %Z')
                    except:
                        pass
            return source
    

提交回复
热议问题