[Solved] Python Error: datetime.datetime is not JSON serializable

Question:

The project is developed with Django, and the returned data contains a time field. When JSON. Dumps(), it will prompt: datetime. Datetime is not JSON serializable

Solution:

import json  
from datetime import date, datetime
  
class DateEncoder(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 it, return will do

return HttpResponse(json.dumps(rows, cls=DateEncoder))

Similar Posts: