How to Fix – “datetime.datetime not JSON serializable” in Python?
Last Updated :
26 Apr, 2025
In this article, we are going to learn how to fix the error “datetime.datetime not JSON serializable” in Python.
datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.datetime object directly to a JSON string using the JSON module in Python.
What is JSON serializable?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write and easy for machines to parse and generate. It is a way of representing data in a format that can be easily converted to and from JavaScript objects. JSON serialization refers to the process of converting a Python object into a JSON-formatted string. JSON-serializable means an object which can be represented in JSON format. For example, a Python dictionary can be easily converted to a JSON-formatted string using the JSON module:
Python3
import json
data = {
"name" : "John Smith" ,
"age" : 30 ,
"address" : {
"street" : "123 Main St" ,
"city" : "Anytown" ,
"state" : "CA" ,
"zip" : "12345"
},
"phoneNumbers" : [
{ "type" : "home" , "number" : "555-555-5555" },
{ "type" : "work" , "number" : "555-555-5555" }
]
}
json_data = json.dumps(data)
print (json_data)
|
Output:
{"name": "John Smith",
"age": 30,
"address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345"},
"phoneNumbers": [{"type": "home", "number": "555-555-5555"},
{"type": "work", "number": "555-555-5555"}]}
To serialize a datetime.datetime object to JSON, you will need to convert it to a format that is compatible with JSON, such as a string.
Serialize a Python datetime.datetime object
If we are trying to serialize a Python datetime.datetime object using the json module and we are getting the error “TypeError: datetime.datetime not JSON serializable”, it means that the JSON module does not know how to convert the datetime object to a JSON-serializable format. Let us have a look at an example of this error.
Python3
import json
import datetime
now = datetime.datetime.now()
json.dumps(now)
|
Output:
Traceback (most recent call last):
File "c:\Users\Desktop\geekforgeeks\gfg6.py", line 5, in <module>
json.dumps(now)
File "C:\Users\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Users\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type datetime is not JSON serializable
Method 1: Using the json.dumps() function
The json.dumps() is a function in the json module of Python that is used to convert a Python object into a JSON-formatted string. It takes an object as its argument and returns a string representation of the object in JSON format.
The datetime.datetime object in Python is not directly JSON serializable, meaning it cannot be converted to a JSON-formatted string using json.dumps without additional steps. To overcome this error, you can use the default argument of the json.dumps function to specify a custom function that will be called to handle non-serializable objects.
Python3
import json
import datetime
def serialize_datetime(obj):
if isinstance (obj, datetime.datetime):
return obj.isoformat()
raise TypeError( "Type not serializable" )
dt = datetime.datetime.now()
json_data = json.dumps(dt, default = serialize_datetime)
print (json_data)
|
Output: This will output a JSON-serialized string that represents the datetime object in ISO format (e.g. “2022-12-31T23:59:59.999999”). We can then use this string to send the datetime object over the network or store it in a file.
"2023-01-13T09:45:04.386958"
Method 2: Using the datetime module’s strftime() method
The strftime() method of the datetime module in Python is used to format a datetime object into a string representation. The method takes a format string as an argument, which defines the desired output format. The format codes used in the format string are similar to those used in the C library function strftime(). The formatted string can then be used for display, storage, or other purposes.
To use the strftime() method to convert a datetime object to a JSON serializable string, we have to first use the strftime() method to format the datetime object into a string with a desired format, and then pass the resulting string to the json.dumps() function.
Python3
import json
import datetime
dt = datetime.datetime.now()
dt_str = dt.strftime( "%Y-%m-%d %H:%M:%S" )
json_data = json.dumps(dt_str)
print (json_data)
|
Output: This will output a JSON-serialized string that represents the datetime object in the format “YYYY-MM-DD HH:MM:SS” (e.g. “2022-12-31 23:59:59”).
"2023-01-13 09:49:07"
Similar Reads
Fix Type Error : NumPy array is not JSON serializable
In this article, we will see how to fix TypeError: Object of type ndarray is not JSON serializable when we are converting a NumPy ndarray object to a JSON string. What is "TypeError: Object of type ndarray is not JSON serializable"?The error "TypeError: Object of type ndarray is not JSON serializabl
4 min read
How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more
3 min read
How to add time onto a DateTime object in Python
In this article, we will discuss the addition of time onto a specified DateTime object in Python. The effect of this will produce a new DateTime object. This addition can be performed by using datetime.timedelta() function. The timedelta() function is used for calculating differences in dates and al
2 min read
How to Fix"dict_keys' object is not subscriptable" in Python
The error message "dict_keys' object is not subscriptable" in Python typically occurs when try to access an element of the dictionary using the square brackets[ ] but we are attempting to do so on a dict_keys object instead of the dictionary itself. What is "dict_keys' object is not subscriptable" i
2 min read
How to make a timezone aware datetime object in Python
In this example, we are going to see how to make a timezone-aware DateTime object in Python. Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation. Checking if an object is
4 min read
How to convert timestamp string to datetime object in Python?
Python has a module named Datetime to work with dates and times. We did not need to install it separately. It is pre-installed with the Python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC. Input: "2023-07-21 10:30:45"Output: 2023-07-21 10:
2 min read
Serializing JSON data in Python
Serialization is the process of encoding the from naive data type to JSON format. The Python module json converts a Python dictionary object into JSON object, and list and tuple are converted into JSON array, and int and float converted as JSON number, None converted as JSON null. Letâs take a look
2 min read
How to convert DateTime to integer in Python
Python provides a module called DateTime to perform all the operations related to date and time. It has a rich set of functions used to perform almost all the operations that deal with time. It needs to be imported first to use the functions and it comes along with python, so no need to install it s
2 min read
How to convert Python's .isoformat() string back into datetime object
In this article, we will learn how to convert Pythons .isoFormat() string back into a datetime object. Here we are using the current time and for that, we will store the current time in the current_time variable. The function now() of this module, does the job perfectly. Example: Getting current tim
1 min read
Python - Convert excel serial date to datetime
This article will discuss the conversion of an excel serial date to DateTime in Python. The Excel "serial date" format is actually the number of days since 1900-01-00 i.e., January 1st, 1900. For example, the excel serial date number 43831 represents January 1st, 2020, and after converting 43831 to
3 min read