close

[Solved] TypeError: datetime.datetime is not JSON serializable

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error TypeError: datetime.datetime is not JSON serializable in Python. So Here I am Explain to you all the possible solutions here.

Without Wasting your time, Lets start This Article to Solve This Error.

How To Solve TypeError: datetime.datetime is not JSON serializable?

Question: How To Solve TypeError: datetime.datetime is not JSON serializable?
Answer: To Solve TypeError: datetime.datetime is not JSON serializable Just Convert the date to a string. the second solution is to just converts and datetime.date objects to strings.

Solution 1 : Convert the date to a string

Convert the date to a string

sample['somedate'] = str( datetime.utcnow() )

Solution 2 : Use json.dumps

Here is my solution:

import json


class DatetimeEncoder(json.JSONEncoder):
    def default(self, obj):
        try:
            return super().default(obj)
        except TypeError:
            return str(obj)

Then you can use it like that:

json.dumps(dictionnary, cls=DatetimeEncoder

Solution 3 : Use json.JSONEncoder

I have just encountered this problem and my solution is to subclass json.JSONEncoder:

from datetime import datetime
import json

class DateTimeEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()

        return json.JSONEncoder.default(self, o)

In your call do something like: json.dumps(yourobj, cls=DateTimeEncoder) The .isoformat() I got from one of the answers above.

Solution 4 : converts datetime.datetime objects to strings.

just converts datetime.datetime and datetime.date objects to strings.

from datetime import date, datetime

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError ("Type %s not serializable" % type(obj))

This json_serial function can be used as follows:

from datetime import datetime
from json import dumps

print dumps(datetime.now(), default=json_serial)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment