Last modified: Apr 24, 2026 By Alexander Williams
Fix datetime Not JSON Serializable Error
If you work with Python and JSON, you may see this error: TypeError: object of type datetime is not JSON serializable. It happens when you try to convert a datetime object to JSON format. JSON only supports basic types like strings, numbers, lists, and dictionaries. Python's datetime is not one of them.
This article explains why this error occurs and how to fix it. We will use simple examples and short code snippets. You will learn three reliable methods to serialize datetime objects. By the end, you can handle this error with confidence.
Why Does This Error Happen?
JSON is a text format for data exchange. It does not have a native type for dates or times. Python's datetime module creates objects for dates and times. When you pass a datetime object to json.dumps(), Python does not know how to convert it. This raises the TypeError.
Here is a simple example that triggers the error:
import json
from datetime import datetime
# Create a datetime object
now = datetime.now()
# Try to serialize it to JSON
data = {"current_time": now}
json_string = json.dumps(data) # This raises TypeError
TypeError: Object of type datetime is not JSON serializable
The error stops your code. You must convert the datetime object to a JSON-friendly type before serialization.
Method 1: Convert datetime to String
The simplest fix is to convert the datetime object to a string. Use the str() function or the isoformat() method. The isoformat() method returns a standard ISO 8601 string, which is widely accepted.
import json
from datetime import datetime
now = datetime.now()
# Convert datetime to ISO string
now_str = now.isoformat()
data = {"current_time": now_str}
json_string = json.dumps(data)
print(json_string)
{"current_time": "2025-04-04T14:30:00.123456"}
This method is fast and easy. However, when you read the JSON back, you get a string, not a datetime object. You must parse the string manually using datetime.fromisoformat().
Method 2: Use a Custom JSON Encoder
For more control, create a custom JSON encoder. Inherit from json.JSONEncoder and override the default() method. This method is called for objects that are not serializable by default.
import json
from datetime import datetime
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
# Let the base class handle other types or raise error
return super().default(obj)
now = datetime.now()
data = {"current_time": now}
json_string = json.dumps(data, cls=DateTimeEncoder)
print(json_string)
{"current_time": "2025-04-04T14:30:00.123456"}
This approach keeps your code clean. You can reuse the DateTimeEncoder class anywhere in your project. It also handles other non-serializable types if you extend the logic.
For more on fixing Python errors, see our guide on Python TypeError: Causes and Fixes. It covers common TypeError scenarios and solutions.
Method 3: Use the default Parameter in json.dumps
The json.dumps() function accepts a default parameter. You can pass a function that converts non-serializable objects. This is like a shortcut for a custom encoder.
import json
from datetime import datetime
def serialize_datetime(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} not serializable")
now = datetime.now()
data = {"current_time": now}
json_string = json.dumps(data, default=serialize_datetime)
print(json_string)
{"current_time": "2025-04-04T14:30:00.123456"}
This method is concise. It works well for small scripts or one-off conversions. For larger projects, the custom encoder class is more maintainable.
Handling Multiple datetime Objects
Sometimes your data has many datetime objects. The custom encoder or default function handles them all at once. Here is an example with a list of datetimes:
import json
from datetime import datetime, timedelta
# Create a list of datetime objects
dates = [datetime.now(), datetime.now() + timedelta(days=1), datetime.now() + timedelta(days=2)]
# Use custom encoder
json_string = json.dumps(dates, cls=DateTimeEncoder)
print(json_string)
["2025-04-04T14:30:00.123456", "2025-04-05T14:30:00.123456", "2025-04-06T14:30:00.123456"]
All datetimes are converted to strings automatically. This saves you from writing loops.
What About date and time Objects?
The same error can happen with date and time objects. The solutions above work for them too. Just check for date or time in your custom encoder or default function. Use isoformat() on each type.
import json
from datetime import date, time
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime, date, time)):
return obj.isoformat()
return super().default(obj)
today = date.today()
current_time = time(14, 30)
data = {"date": today, "time": current_time}
print(json.dumps(data, cls=DateTimeEncoder))
{"date": "2025-04-04", "time": "14:30:00"}
Conclusion
The TypeError: object of type datetime is not JSON serializable is common but easy to fix. You can convert datetime to a string, use a custom JSON encoder, or pass a default function. Each method works well for different needs.
For simple tasks, the isoformat() string conversion is fastest. For reusable code, create a DateTimeEncoder class. For quick scripts, use the default parameter. Always remember to parse the string back to datetime when reading JSON.
Understanding this error helps you write better Python code. It also prepares you for other serialization challenges. For more tips on fixing Python errors, check out our Python TypeError: Causes and Fixes article.
Now you can handle datetime serialization with ease. Happy coding!