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:
- Convert the
datetimeobject to a string: Before serializing the object, you can convert thedatetimeobject to a string using thestrftimemethod.
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)
- Use a custom JSON encoder: You can define a custom function to handle the
datetimeobject 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)
- Use a lambda function with
defaultargument: Instead of creating a custom encoder class, you can use a lambda function with thedefaultargument of thejson.dumpsmethod.
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.