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

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

I have a basic dict as follows:

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


        
30条回答
  •  再見小時候
    2020-11-22 03:47

    Here is my solution:

    import json
    
    
    class DatetimeEncoder(json.JSONEncoder):
        def default(self, obj):
            try:
                return super().default(obj)
            except TypeError:
                return str(obj)
    

    Then you can use it like that:

    json.dumps(dictionnary, cls=DatetimeEncoder)
    

提交回复
热议问题