How to fix "TypeError: Object of type datetime is not JSON serializable" in python ?

Published: April 04, 2022

Updated: December 09, 2022

Tags: Python; JSON;

DMCA.com Protection Status

Example of how to fix the TypeError: Object of type datetime is not JSON serializable" in python:

Let's consider an example:

Create a datetime object

Reminder: to create a datetime object in python

import datetime

x = datetime.datetime.now()

gives for example

2022-04-04 14:16:59.604425

which is a datetime object

Create a json file

Now if we try to create a json file using a dictionary with a datetime object inside (see json — JSON encoder and decoder):

import json

dict = {"member #002":{"first name": "John", "last name": "Doe", "age": 34, "Date":datetime.datetime.now()},
                "member #003":{"first name": "Elijah", "last name": "Baley", "age": 27, "Date":datetime.datetime.now()},
                "member #001":{"first name": "Jane", "last name": "Doe", "age": 42, "Date":datetime.datetime.now()}}

with open('data.json', 'w') as fp:
        json.dump(dict, fp,  indent=4)

it will returns the following error:

TypeError: Object of type datetime is not JSON serializable

To fix that a straightforward solution is to add the option "default=str":

        json.dump(dict, fp,  indent=4, default=str)