Open In App

How to Fix – “datetime.datetime not JSON serializable” in Python?

Last Updated : 05 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Importing required module
import json
import datetime
  
# Store time in "now"
now = datetime.datetime.now()
  
# Serializing time stored in 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
  
# Define a custom function to serialize datetime objects
def serialize_datetime(obj):
    if isinstance(obj, datetime.datetime):
        return obj.isoformat()
    raise TypeError("Type not serializable")
  
  
# Create a datetime object
dt = datetime.datetime.now()
  
# Serialize the object using the custom function
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




# Importing required modules
import json
import datetime
  
# Create a datetime object
dt = datetime.datetime.now()
  
# Convert the datetime object to a string in a specific format
dt_str = dt.strftime("%Y-%m-%d %H:%M:%S")
  
# Serialize the string using the json module
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"


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads