TypeError: Object of type Timestamp is not JSON serializable

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Baraa Jalahej

TypeError: Object of type Timestamp is not JSON serializable #

The Python "TypeError: Object of type Timestamp is not JSON serializable" occurs when we try to convert a Timestamp object to a JSON string. To solve the error, convert the Timestamp object to str before serializing it to JSON.

Here is an example of how the error occurs.

main.py
import json import pandas as pd tstamp = pd.Timestamp('2023-01-01T12') # ⛔️ TypeError: Object of type Timestamp is not JSON serializable json_str = json.dumps({'created_at': tstamp})

We tried passing a Timestamp object to the json.dumps() method but the method doesn't handle Timestamp objects by default

To solve the error, use the built-in str() class to convert he Timestamp to str before serializing it.

main.py
import json import pandas as pd tstamp = pd.Timestamp('2023-01-01T12') # ✅ convert to str json_str = json.dumps({'created_at': str(tstamp)}) print(json_str) # 👉️ '{"created_at": "2023-01-01 12:00:00"} print(type(json_str)) # 👉️ <class 'str'>

The default JSON encoder handles str values, so we can use a native Python str instead of a Timestamp when serializing to JSON.

The json.dumps method converts a Python object to a JSON formatted string.

Alternatively, you can extend from the JSONEncoder class and handle the conversions in a default method.

main.py
import json import pandas as pd class PdEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, pd.Timestamp): return str(obj) return json.JSONEncoder.default(self, obj) tstamp = pd.Timestamp('2023-01-01T12') json_str = json.dumps({'created_at': tstamp}, cls=PdEncoder) print(json_str) # 👉️ '{"created_at": "2023-01-01 12:00:00"} print(type(json_str)) # 👉️ <class 'str'>

We extended from the JSONEncoder class.

The JSONEncoder class supports the following objects and types by default.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

Notice that the JSONEncoder class doesn't support Timestamp to JSON conversion by default.

We can handle this by extending from the class and implementing a default() method that returns a serializable object.

main.py
import json import pandas as pd class PdEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, pd.Timestamp): return str(obj) return json.JSONEncoder.default(self, obj)

If the passed in value is a Timestamp, we convert it to a str and return the result.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

In all other cases, we let the base classes' default method do the serialization.

To use a custom JSONEncoder, specify it with the cls keyword argument in your call to the json.dumps() method.

main.py
import json import pandas as pd class PdEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, pd.Timestamp): return str(obj) return json.JSONEncoder.default(self, obj) tstamp = pd.Timestamp('2023-01-01T12') json_str = json.dumps({'created_at': tstamp}, cls=PdEncoder) print(json_str) # 👉️ '{"created_at": "2023-01-01 12:00:00"} print(type(json_str)) # 👉️ <class 'str'>

If you don't provide the cls kwarg, the default JSONEncoder is used.

Use the search field on my Home Page to filter through my more than 1,000 articles.