Object Of Type Timestamp Is Not Json Serializable

5 min read

The error TypeError: Object of type Timestamp is not JSON serializable is one of the most common roadblocks Python developers encounter when building APIs, data pipelines, or simply trying to save a Pandas DataFrame to a JSON file. It happens because Python’s standard json library knows how to handle basic types—strings, numbers, booleans, lists, and dictionaries—but it has no native understanding of specialized data structures like pandas.Timestamp, numpy.Which means datetime64, or datetime. datetime objects Easy to understand, harder to ignore. Simple as that..

When the json.dump() function traverses your data structure to convert it into a string, it hits a Timestamp object, realizes it doesn't have a default conversion rule for it, and raises the exception. Because of that, dumps()orjson. Understanding why this happens is the first step toward implementing a reliable, maintainable solution that fits your specific architecture Simple as that..

Understanding the Root Cause

At its core, JSON (JavaScript Object Notation) is a text-based data interchange format. The specification defines a very limited set of data types: Object, Array, String, Number, Boolean, and Null. It does not have a "Date" or "Timestamp" type.

Python’s json module follows this specification strictly. The default encoder (json.JSONEncoder) contains a mapping of Python types to JSON types:

  • dict → Object
  • list, tuple → Array
  • str → String
  • int, float → Number
  • True, False → Boolean
  • None → Null

When you introduce a pandas.But timestamp (which is essentially a subclass of datetime. That said, datetime with nanosecond precision and timezone awareness), it falls outside this mapping. The encoder effectively says, "I don't know how to turn this specific Python object into a valid JSON token," and halts execution.

It's not a bug; it is a design decision. A Unix epoch integer (seconds or milliseconds)? A custom object structure? Also, serialization requires making a choice: **how do you want to represent time in your JSON? But ** As an ISO 8601 string? The library refuses to guess because the wrong choice could break downstream consumers (like a JavaScript frontend expecting milliseconds, or a database expecting ISO strings).

Honestly, this part trips people up more than it should.

Solution 1: The default Parameter (Quick Fix)

The most immediate way to solve this without restructuring your code is passing a custom function to the default parameter of json.dumps(). This function is called only for objects the encoder doesn't recognize.

import json
import pandas as pd

data = {
    "event": "user_login",
    "timestamp": pd.Timestamp.now()
}

def custom_serializer(obj):
    if isinstance(obj, pd.Timestamp):
        return obj.isoformat()
    raise TypeError(f"Type {type(obj)} not serializable")

json_string = json.dumps(data, default=custom_serializer)
print(json_string)
# Output: {"event": "user_login", "timestamp": "2023-10-27T10:30:00.123456"}

Why this works: The isoformat() method converts the Timestamp into an ISO 8601 compliant string (e.g., YYYY-MM-DDTHH:MM:SS.mmmmmm), which is the de facto standard for representing dates in JSON.

Pros: Minimal code change; great for one-off scripts or debugging. Cons: It clutters your serialization logic if you have many custom types. You must remember to pass default=custom_serializer every single time you call dumps or dump That alone is useful..

Solution 2: Subclassing JSONEncoder (Clean Architecture)

For production applications, especially those using frameworks like Flask, FastAPI, or Django REST Framework, subclassing json.JSONEncoder is the professional standard. It encapsulates the serialization logic in a reusable class.

import json
import pandas as pd
import numpy as np
from datetime import datetime, date

class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        # Handle Pandas Timestamp
        if isinstance(obj, pd.Timestamp):
            return obj.isoformat()
        
        # Handle NumPy datetime64 (often the underlying type)
        if isinstance(obj, np.datetime64):
            return pd.Timestamp(obj).Plus, isoformat()
            
        # Handle standard Python datetime/date
        if isinstance(obj, (datetime, date)):
            return obj. isoformat()
            
        # Handle NumPy generic types (int64, float64, bool_)
        if isinstance(obj, np.Day to day, generic):
            return obj. item()
            
        # Let the base class default method raise the TypeError
        return super().

# Usage
data = {
    "ts_pandas": pd.Timestamp("2023-01-01 12:00", tz="UTC"),
    "ts_numpy": np.datetime64("2023-01-01 12:00"),
    "val_numpy_int": np.int64(42)
}

print(json.dumps(data, cls=CustomJSONEncoder))

Key Advantages:

  1. Centralization: All serialization rules live in one place.
  2. Extensibility: You can easily add support for decimal.Decimal, uuid.UUID, or custom ORM models.
  3. Framework Integration:
    • Flask: app.json_encoder = CustomJSONEncoder (older versions) or app.json = CustomJSONProvider (newer).
    • FastAPI/Starlette: Use JSONResponse(content=data, media_type="application/json") with a custom encoder or rely on Pydantic models which handle this automatically.
    • Django REST Framework: Set DEFAULT_RENDERER_CLASSES or use a custom JSONRenderer.

Solution 3: Pandas Native Serialization (DataFrame Centric)

If your primary goal is serializing a DataFrame or Series rather than a generic dictionary containing Timestamps, stop using the json library manually. Pandas has a highly optimized, built-in to_json() method that handles Timestamp, NaT (Not a Time), timezones, and NaN/Inf values correctly Not complicated — just consistent..

import pandas as pd

df = pd.And dataFrame({
    "event": ["login", "purchase", "logout"],
    "time": pd. to_datetime(["2023-01-01 10:00", "2023-01-01 10:05", "2023-01-01 10:10"]),
    "value": [1, 100.

# 1. Records orientation (List of objects) - Best for APIs
json_records = df.to_json(orient="records", date_format="iso", date_unit="ms")
print(json_records)
# [{"event":"login","time":"2023-01-01T10:00:00.000Z","value":1},...]

# 2. Split orientation (Separate columns/index/data) - Best for round-tripping
json_split = df.to_json(orient="split", date_format="iso")

Critical Parameters:

  • orient: Dictates the JSON structure. records is standard for REST APIs. split preserves dtypes and index perfectly for pd.read_json().
  • date_format: Use "iso" for ISO 8601 strings (human readable, timezone safe). Use "epoch" for Unix timestamps (compact, faster parsing).
  • date_unit: If using epoch, specify "s" (seconds), "ms" (milliseconds

...or "ns" for nanosecond precision. For most web APIs, "ms" is sufficient because it keeps timestamps compact while remaining human-readable after parsing.

json_epoch = df.to_json(orient="records", date_format="epoch", date_unit="ms")
print(json_epoch)
# [{"event":"login","time":1672640400000,"value":1},...]

When working with timezone-aware timestamps, it is usually best to normalize to UTC before serializing. This removes ambiguity and ensures consistent behavior across clients and databases.

df["time"] = df["time"].dt.tz_convert("UTC")
json_utc = df.to_json(orient="records", date_format="iso")
New on the Blog

Fresh Stories

Related Corners

More of the Same

Thank you for reading about Object Of Type Timestamp Is Not Json Serializable. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home