Solve object of type datetime is not JSON serializable in python

object of type datetime is not json serializable

When we attempt to serialize a Python datetime object to JSON. We get TypeError: Object of type datetime is not JSON serializable problem. This is because the JSON module does not support the object from the datetime module.

To solve this problem we need to convert datetime object to a string format using JSON module that can be serialized.

When does "object of type datetime is not json serializable" in python occur ?

JSON stands for javascript object notation which is a lightweight data interchange format. JSON only supports basic datatypes such as strings, numbers, booleans, arrays, and dictionaries. JSON by default doesn’t support representation of complex objects like datetime.  

When we attempt to serialize a datetime object directly into JSON we get an error. we will show you two examples where an object of type datetime is not JSON serializable error occurs

I have created an empty dictionary called “event_details”  which contains two keys title and time. The time key is storing the current datetime. When we try to serialize the data using json.dumps() function we get an error.

Example 1
import datetime
import json

event_details = {}
event_details['title'] = "Error"
event_details['time'] =datetime.datetime.now() 

json_data = json.dumps(event_details)
Example 2
import json
from datetime import datetime

data = {
    "timestamp": datetime.now()
}

json_data = json.dumps(data)

Error we get

TypeError                                 Traceback (most recent call last)
Cell In[6], line 8
      5 event_details['title'] = "Error"
      6 event_details['time'] =datetime.datetime.now() 
----> 8 json_data = json.dumps(event_details)

in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    226 # cached encoder
    227 if (not skipkeys and ensure_ascii and
    228     check_circular and allow_nan and
    229     cls is None and indent is None and separators is None and
    230     default is None and not sort_keys and not kw):
--> 231     return _default_encoder.encode(obj)
    232 if cls is None:
    233     cls = JSONEncoder

 in JSONEncoder.encode(self, o)
    195         return encode_basestring(o)
    196 # This doesn't pass the iterator directly to ''.join() because the
    197 # exceptions aren't as detailed.  The list call should be roughly
    198 # equivalent to the PySequence_Fast that ''.join() would do.
--> 199 chunks = self.iterencode(o, _one_shot=True)
    200 if not isinstance(chunks, (list, tuple)):
    201     chunks = list(chunks)
...
    178     """
--> 179     raise TypeError(f'Object of type {o.__class__.__name__} '
    180                     f'is not JSON serializable')

TypeError: Object of type datetime is not JSON serializable

How to solve object of type datetime is not json serializable in python ?

We have two ways to solve this error.

  1. Convert datetime to string .
  2. Custom JSON encoder.

Convert datetime to string using strftime() method

We can convert datetime object to a string using the strftime method. The strftime method allows us for more flexibility in terms of date and time format. You can follow the documentation here for more information. Code
import datetime
import json

dt_now = datetime.datetime.now()
cus_date=dt_now.strftime("%Y-%m-%dT%H:%M:%SZ")
event={'name':'error','time':cus_date}
json_string = json.dumps(event)  
print(json_string)  

output
{"name": "error", "time": "2024-05-20T14:04:53Z"}

Convert datetime to string using isoformat() method

When we use isoformat method the datetime object is automatically converted into string . The date time format is in this form “YYYY-MM-DDTHH:MM:SS.ffffffZ” which is widely accepted and compatible  with JSON. Code
import datetime
import json

dt_now = datetime.datetime.now()
json_string = json.dumps({'time':dt_now.isoformat()})
print(json_string)  
Output
{"time": "2024-05-20T14:21:43.326789"}

Using 'default' parameter in json.dumps() function

The ‘default’ parameter in json.dumps() function is used to specify a custom serialization function for objects that are not natively json serializable. Whenever json.dumps() runs into a object for which it doesn’t know how to serialize it will call the ‘default’ function. When we provide ‘default=str’ it means whenever json.dumps() function sees a complex object like datetime, it will call str() function. The str() function will convert the object to string representation. Ensuring  all objects are converted to string before being serialized to JSON. Code
import datetime
import json

dt_now = datetime.datetime.now()
event={'name':'error solved','time':dt_now}
json_string = json.dumps(event, default=str) 
print(json_string) 
Output
'{"name": "error solved", "time": "2024-05-20 15:01:04.245225"}'

Custom JSON encoder

Creating a custom json encoder to handle datetime object is also a option. The custom encoder will be called every time when we come across a object that is not serializable. Code
import datetime
import json

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

# Data to be serialized
data = {"name": "Mangesh", "date": datetime.datetime(2023, 5, 20)}

# custom encoder
json_data = json.dumps(data, cls=DateEncoder)
print(json_data)
Output
{"name": "Mangesh", "date": "2023-05-20T00:00:00"}
The class DateEncoder inherits from json.JSONEncoder. We are overriding the ‘default’ function from json.JSONEncoder.default(). Inside that function, we check for whether the object is datetime type. If yes, then we convert the datetime object to string using isoformat() function. If the object is not a datetime object then we call json.JSONEncoder.default() function with the object to handle the necessary serialization.

DjangoJSONEncoder for Serialization

If you are using the Django framework you can use the native DjangoJSONEncoder  serializer to serialize datetime. Code
import json
import datetime
from django.core.serializers.json import DjangoJSONEncoder


task = {
    "id": 123,
    "title": "Complete project",
    "deadline": datetime.datetime(2024, 5, 20, 18, 0, 0)  
}

# Serialize the dictionary using DjangoJSONEncoder
serialized_task = json.dumps(task, cls=DjangoJSONEncoder)
print(f"Serialized JSON data: \n {serialized_task}")
Output
Serialized JSON data: 
 {"id": 123, "title": "Complete project",
 "deadline": "2024-05-20T18:00:00"}

Conclusion

In this blog, we learned how to make a datetime object JSON serializable in Python by using the JSON module. You can also explore the difference between continue and pass.

2 thoughts on “Solve object of type datetime is not JSON serializable in python”

  1. Pingback: How to write a list to a file in python -

  2. Pingback: How To Use Lambda Function In List Comprehension In Python -

Comments are closed.