How to overcome “datetime.datetime not JSON serializable”?

后端 未结 30 2708
梦谈多话
梦谈多话 2020-11-22 03:31

I have a basic dict as follows:

sample = {}
sample[\'title\'] = \"String\"
sample[\'somedate\'] = somedatetimehere
         


        
30条回答
  •  无人及你
    2020-11-22 03:59

    I have just encountered this problem and my solution is to subclass json.JSONEncoder:

    from datetime import datetime
    import json
    
    class DateTimeEncoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, datetime):
                return o.isoformat()
    
            return json.JSONEncoder.default(self, o)
    

    In your call do something like: json.dumps(yourobj, cls=DateTimeEncoder) The .isoformat() I got from one of the answers above.

提交回复
热议问题