Close

2023-10-23

Object of type datetime is not JSON serializable.

Object of type datetime is not JSON serializable

The error “Object of type datetime is not JSON serializable” occurs when you try to serialize a Python datetime object into JSON format using the json module. The json module does not know how to convert a datetime object into a JSON-compatible format by default.

To resolve this issue, you can use one of the following methods:

  1. Convert the datetime object to a string: Before serializing the object, you can convert the datetime object to a string using the strftime method.
   import json
   import datetime

   dt = datetime.datetime.now()
   dt_str = dt.strftime('%Y-%m-%d %H:%M:%S')

   data = {'date': dt_str}
   json_str = json.dumps(data)
  1. Use a custom JSON encoder: You can define a custom function to handle the datetime object during the serialization process.
   import json
   import datetime

   class DateTimeEncoder(json.JSONEncoder):
       def default(self, obj):
           if isinstance(obj, datetime.datetime):
               return obj.isoformat()
           return super(DateTimeEncoder, self).default(obj)

   dt = datetime.datetime.now()
   data = {'date': dt}
   json_str = json.dumps(data, cls=DateTimeEncoder)
  1. Use a lambda function with default argument: Instead of creating a custom encoder class, you can use a lambda function with the default argument of the json.dumps method.
   import json
   import datetime

   dt = datetime.datetime.now()
   json_str = json.dumps(data, default=lambda o: o.isoformat() if isinstance(o, datetime.datetime) else None)

Choose the method that best fits your needs. The first method is straightforward but requires you to convert each object manually. The second and third methods are more automated and can handle multiple datetime objects in a data structure.