Typeerror: Object Of Type Timestamp Is Not Json Serializable

9 min read

Understanding TypeError: object of type timestamp is not JSON serializable

When you attempt to convert a Python object into JSON—either by calling json.That's why dumps(), sending data over an API, or saving it to a file—you might encounter a TypeError: object of type timestamp is not JSON serializable. This error tells us that somewhere inside your payload a value of type timestamp (often a datetime or pd.Timestamp) exists, but the standard JSON encoder does not know how to turn that particular object into a JSON‑compatible representation. Recognizing this issue early saves you from debugging nightmares later and helps you build more reliable applications. In this article we’ll explore why the error happens, walk through common sources, and provide clear, step‑by‑step solutions so you can reliably serialize any timestamp field without surprises.


Introduction

Python’s built‑in datetime module supplies rich date‑time classes such as datetime, date, and timedelta. By understanding the root causes and applying the right conversion techniques, you can easily embed timestamps in APIs, configuration files, or web responses. Consider this: when a program tries to dump a dictionary that contains a datetime instance, the default json implementation raises the mentioned TypeError. While these objects are indispensable for scheduling, logging, and data analysis, they are not natively supported by the JSON format. This guide covers everything from the basic reasons behind the error to advanced strategies, ensuring your JSON payloads stay clean and valid Which is the point..

Common Causes & When It Happens

  • Loading data from services: Many APIs return timestamps as ISO strings, but sometimes they send them as native datetime objects or pandas.Timestamp objects.
  • Storing in databases: Some ORMs or persistence layers store dates as datetime instances before exporting them.
  • Using Pandas: DataFrames often contain columns labeled "created_at" populated with pd.Timestamp.
  • Manual construction: You may build dictionaries by concatenating date parts (year, month, …) instead of passing a single datetime object.

Each scenario triggers the same serialization problem because the JSON encoder only knows how to handle primitive types (str, int, float, bool, None). Anything else—including custom objects—must be provided explicitly via a default handler or converted beforehand Easy to understand, harder to ignore. Worth knowing..

Step‑by‑Step Fixes

Below is a practical checklist you can follow. Choose the method that matches your codebase and libraries.

1. Convert the timestamp to a string before encoding

The simplest remedy is to transform the datetime (or pd.Timestamp) into its ISO‑formatted string representation. For example:

import json
from datetime import datetime

dt = datetime(2025, 6, 15, 14, 30, 0)

# Convert to ISO format
dt_str = dt.isoformat()
print(json.dumps({"event": dt_str}))   # works without error

If you’re using Pandas, apply value = value.Day to day, isoformat() or value. strftime('%Y-%m-%dT%H:%M:%S').

2. Add a custom JSON encoder

Python’s json module accepts a callable passed to default. Define a function that handles objects of type datetime:

import json
from datetime import datetime

class DateTimeEncoder(json.value.In practice, timestamp as well
        if hasattr(obj, 'astype'):          # crude check for pandas Timestamp
            return obj. JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.Now, isoformat()
        # Optionally handle pd. isoformat()
        return super().

encoder = DateTimeEncoder()

data = {"ts": datetime.now()}
print(json.dumps(data, cls=encoder))

Now any occurrence of a datetime (or compatible pandas object) will be turned into an ISO string automatically.

3. Use simplejson or ujson with extra plugins

Third‑party JSON libraries sometimes offer better support for non‑standard types. Worth adding: installing simplejson gives you access to simplejson. And dumps(... In real terms, , default=... ) and allows specifying a converter class.

pip install simplejson
import simplejson as sj
data = {"ts": datetime.now()}
print(sj.dumps(data, option=None))   # still needs default, but simplejson handles more cases.

For ultra‑fast encoding, ujson is another alternative, though it generally requires manual handling of custom types Simple as that..

4. apply environment variables or config settings

In larger projects

In larger projects, serialization logic often lives in a shared utility module or a configuration layer so that every service, script, and test uses the same rules. A common pattern is to expose a single json_dumps wrapper that injects the custom encoder automatically:

# utils/json_utils.py
import json
from datetime import datetime, date
from decimal import Decimal
from uuid import UUID

class ProjectEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()
        if isinstance(obj, Decimal):
            return str(obj)          # preserve precision
        if isinstance(obj, UUID):
            return str(obj)
        return super().

def json_dumps(obj, **kwargs):
    kwargs.setdefault("cls", ProjectEncoder)
    kwargs.setdefault("ensure_ascii", False)
    return json.

Now the rest of the codebase simply imports `json_dumps` instead of the standard library function, guaranteeing consistent output without sprinkling `cls=ProjectEncoder` everywhere.

### 5. Adopt a serialization library (Pydantic, msgspec, attrs)

Modern Python projects frequently rely on data‑validation libraries that ship with built‑in JSON serialization. **Pydantic v2**, for instance, handles `datetime`, `date`, `Decimal`, `UUID`, and even custom types out of the box:

```python
from pydantic import BaseModel
from datetime import datetime
from decimal import Decimal

class Event(BaseModel):
    name: str
    occurred_at: datetime
    amount: Decimal

event = Event(name="purchase", occurred_at=datetime(2025, 6, 15, 14, 30), amount=Decimal("19.99"))
print(event.model_dump_json())
# {"name":"purchase","occurred_at":"2025-06-15T14:30:00","amount":"19.

If you prefer a zero‑dependency, ultra‑fast alternative, **msgspec** provides similar ergonomics with a fraction of the overhead:

```python
import msgspec
from datetime import datetime

class Event(msgspec.Struct):
    name: str
    occurred_at: datetime

print(msgspec.json.encode(Event("login", datetime.utcnow())))

Both libraries eliminate the need for manual default handlers and keep the serialization logic declarative That's the whole idea..

6. Handle ORM objects and nested structures

When working with SQLAlchemy, Django ORM, or Tortoise models, the objects returned from queries are not plain dictionaries. A reliable approach is to define a schema layer (Pydantic, msgspec, or even dataclasses + dataclass-wizard) that maps ORM instances to serializable DTOs:

# schemas.py
from pydantic import BaseModel
from datetime import datetime
from typing import Optional

class UserRead(BaseModel):
    id: int
    email: str
    created_at: datetime
    last_login: Optional[datetime] = None

    class Config:
        from_attributes = True   # enables ORM mode in Pydantic v2
# views.py
from schemas import UserRead
from models import User

user = session.get(User, 42)
return UserRead.model_validate(user).model_dump_json()

This isolates the API contract from the database schema and ensures that every datetime field is rendered as an ISO‑8601 string automatically It's one of those things that adds up..


Quick Reference Cheat Sheet

Situation Recommended Fix
One‑off script, few timestamps value.isoformat() before json.dumps
Multiple modules, stdlib only Central ProjectEncoder + wrapper json_dumps
High‑throughput services msgspec or orjson (with default for custom types)
Data validation + serialization Pydantic BaseModel / TypeAdapter
ORM‑heavy codebase Pydantic from_attributes=True or dedicated DTO layer
Legacy code, minimal changes Monkey‑patch `json.JSONEncoder.

Conclusion

The “Object of type datetime is not JSON serializable” error is not a bug—it is a reminder that JSON only understands a handful of primitive types. By converting timestamps to ISO‑8601 strings before they reach the encoder, installing a project‑wide custom encoder, or adopting a modern serialization library like Pydantic or msgspec, you eliminate the friction once and for all. On the flip side, choose the strategy that aligns with your stack’s complexity: a tiny utility wrapper for small codebases, a schema‑driven approach for API‑centric services, or a high‑performance library for throughput‑critical paths. With a consistent serialization policy in place, datetime handling becomes invisible, letting you focus on business logic instead of encoding errors Most people skip this — try not to..

After you have defined a schema layer that maps ORM instances to plain data containers, the most common remaining hurdle is ensuring that every value the encoder expects—especially those typed as datetime, UUID, or custom business objects—gets rendered correctly. In practice this means deciding whether to rely on the built‑in defaults of a modern serializer, to stitch together small utilities for one‑off scripts, or to adopt a framework‑wide custom encoder.

A single source of truth for JSON encoding

When a codebase grows past a few dozen files, hard‑coding default= functions inside each module quickly becomes error‑prone. A lightweight solution is a project‑level encoder that lives outside the service implementations:

# encoders.py
import datetime
from typing import Any, Union

def encode(obj: Any) -> dict:
    """Return a JSON‑friendly representation of *obj*.On top of that, """
    if isinstance(obj, datetime. And datetime):
        return {"__datetime__": obj. Consider this: date):
        return {"__date__": obj. Day to day, isoformat()}
    # Add any other conversions here (e. Still, isoformat()}
    if isinstance(obj, datetime. g.

You can then drop a thin wrapper around `json.dumps`:

```python
import json
from encoders import encode

def json_dumps(data):
    return json.dumps(encode(data), default=encode)

For higher‑throughput paths consider switching to msgspec, which provides a declarative API and native support for many standard types without needing extra default calls:

import msgs

`

```python
import msgspec

# Define a schema for your data
class User(msgspec.Struct):
    id: int
    name: str
    created_at: datetime.datetime

# Serialize an instance
user = User(id=1, name="Alice", created_at=datetime.datetime.now())
encoded = msgspec.json.encode(user)

With msgspec, you define your data structures once, and the library automatically generates highly optimized encoding and decoding functions. So it natively understands datetime, UUID, decimal. On the flip side, decimal, and many other types without any additional configuration. The performance is often an order of magnitude faster than the standard json module, making it ideal for high-throughput APIs or bulk data exports.

Choosing the right tool for the job

The optimal strategy depends on your project’s constraints:

  • Small scripts or quick fixes: A custom JSONEncoder or a helper function that converts datetimes to ISO strings is sufficient and requires minimal setup.
  • API‑driven services: Adopting a schema library like Pydantic or msgspec brings type safety, validation, and automatic serialization, reducing boilerplate and preventing entire classes of runtime errors.
  • Large legacy systems: Introduce a centralized encoder or a thin wrapper around json.dumps to enforce a consistent conversion policy without touching every module.

By treating JSON serialization as a first‑class concern—rather than an afterthought—you eliminate the “Object of type datetime is not JSON serializable” error at its root. Whether you opt for a lightweight custom encoder, a reliable schema layer, or a high‑performance library, the key is to establish a single, reliable conversion mechanism that all parts of your codebase rely on. This not only saves debugging time in the present but also makes future extensions straightforward, allowing your team to focus on building features instead of wrestling with data formatting Surprisingly effective..

The short version: the error is a signal to formalize how your application represents time and other complex types in the JSON universe. Also, with a clear serialization policy in place, datetime values flow naturally into API responses, logs, and data stores, and you can finally move past the repetitive cycle of patching encoder defaults. The right choice is the one that balances simplicity, performance, and maintainability for your specific context, ensuring that your code remains clean, predictable, and resilient And that's really what it comes down to..

This Week's New Stuff

Fresh Reads

Branching Out from Here

Stay a Little Longer

Thank you for reading about Typeerror: 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