Table of Contents
In Python, the datetime
library allows us to create objects of the datetime
class that can store and process date and time values efficiently. We can manipulate these objects according to our needs using the wide range of functionalities provided by this library.
JSON is a type of encoding for data that is used frequently to facilitate the exchange of data over networks. It stands for JavaScript Object Notation. Due to the heavy influence of objects like dictionaries and lists on this notation, the Python language works very efficiently with such data.
In Python, we have the json
library that contains a wide range of functionalities to work with such type of data. JSON serialization means taking some data and converting it into a JSON string. In Python, this can be achieved using the json.dumps()
function.
When we get the object of type datetime is not JSON serializable
exception in Python, it means that the datetime
object cannot be serialized into a JSON string. This is a TypeError
which means that it is caused due to performing illegal function on the given type of data.
Let us see an example of this exception.
1 2 3 4 5 6 7 8 |
import json from datetime import datetime dt = datetime(2022,5,9,15,20,15) c = {'Date':dt, 'Name': 'Jack'} s = json.dumps(c) print(s) |
Output:
In the above example, we try to serialize a dictionary but the error is thrown because the dictionary contains a datetime
object.
However, we can work around this and solve this exception using different ways.
💡 Quick fix
If you are looking for quick fix, you can just use default parameter with
json.dumps()
to fix the issue.
123 s = json.dumps(c, default = str);
Fix the object of type datetime is not JSON serializable
exception in Python
The following section will discuss the different methods to fix the object of type datetime is not JSON serializable
exception in Python.
Using the default
parameter in the json.dumps()
function
As discussed, the json.dumps()
function is used to serialize some data to a JSON string. This function accepts a default
parameter.
This parameter accepts a function that is applied to the object in case any TypeError
exception is thrown. By using default parameter, the datetime
object can be converted to a string by specifying the value of the parameter as the str
function.
See the following example.
1 2 3 4 5 6 7 8 |
import json from datetime import datetime dt = datetime(2022,5,9,15,20,15) c = {'Date':dt, 'Name': 'Jack'} s = json.dumps(c, default = str) print(s) |
Output:
In the above example, we can see that the exception is avoided due to the presence of the default
parameter and the datetime
object gets converted to a string.
Another function, we can use is the datetime.isoformat()
method. This method returns a provided datetime
object as a string in the ISO format. We can use this method instead of the str
function.
See the following example.
1 2 3 4 5 6 7 8 9 10 11 |
import json from datetime import datetime def fun(ob): if isinstance(ob, datetime): return ob.isoformat() dt = datetime(2022,5,9,15,20,15) c = {'Date':dt, 'Name': 'Jack'} s = json.dumps(c, default = fun) print(s) |
In the above example, we create a function fun
that takes an object and if this object is of type datetime
(checked using the isinstance()
method) then it returns a string of this object in ISO format using the isoformat()
method.
Using the cls
parameter in the json.dumps()
function
We can use the cls
parameter in the json.dumps()
function to serialize incompatible types. We will create a subclass of the json.JSONEncoder
class that by default manages this. We will override the default
method and convert the datetime
object to a string using the str
method.
For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import json from datetime import datetime class DatetimeEncoder(json.JSONEncoder): def default(self, ob): if isinstance(ob, datetime): return str(ob) return json.JSONEncoder.default(self, ob) dt = datetime(2022,5,9,15,20,15) c = {'Date':dt, 'Name': 'Jack'} s = json.dumps(c, cls = DatetimeEncoder) print(s) |
Output:
The DatetimeEncoder
class in the above example is a subclass of the json.JSONEncoder
class. We define the default
method to convert the datetime
objects to strings.
Alternatively, we can also use the isoformat()
method instead of the str
function to get a string representation of the datetime
object.
Using the str
function
In the previous methods, we discussed how to get a string representation of the datetime
object when encountered in the json.dumps()
function. However, we can also just convert the object to a string directly before passing it for serialization using the str()
function.
For example,
1 2 3 4 5 6 7 8 |
import json from datetime import datetime dt = datetime(2022,5,9,15,20,15) c = {'Date':str(dt), 'Name': 'Jack'} s = json.dumps(c) print(s) |
Output:
Also, we can get the string representation using the isoformat()
method.
Further reading:
Conclusion
To conclude, we discussed how to fix the object of type datetime is not JSON serializable
exception in Python. We discussed several methods to tackle this error.
In the first method, we used specified the default
parameter with the str
and isoformat()
functions to convert the datetime
object to a string when encountered in the json.dumps()
function.
Similarly, in the second method, we created a subclass of the json.JSONEncoder
class that has a default method that handles datetime
object in a similar way. We can also convert these objects beforehand as discussed in the final method.