Typeerror: object of type datetime is not json serializable

As developers, we cannot prevent encountering errors like typeerror: object of type datetime is not json serializable.

We do encounter this kind of error when we are working on a Python project.

In this article, we will help you fix the typeerror message mentioned above.

In addition, you will also learn here what typeerror and Python are and some tips to avoid getting typeerrors.

What is typeerror: object of type datetime is not json serializable?

The typeerror: object of type datetime is not json serializable is an error message in Python.

This error happens when we attempt to convert a datetime object into a JSON format using json.dumps() function.

What is JSON?

JSON, or JavaScript Object Notation, is a data interchange format.

It is used to interchange data between programming languages.

And it does not directly support datetime objects. Because of this, this error was triggered.

So, to not get this error, convert the datetime objects into a string representation before serializing them as JSON.

Here is an example code that causes this error:

import json
from datetime import datetime

s_data = {'timestamp': datetime.now()}
json_data = json.dumps(s_data)

Error:

Traceback (most recent call last):
  File "C:\Users\path\s_path\sProject\main.py", line 5, in <module>
    json_data = json.dumps(s_data)
                ^^^^^^^^^^^^^^^^^^
  File "C:\Users\path\path1\Local\Programs\Python\Python311\Lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\path\path1\Local\Programs\Python\Python311\Lib\json\encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\path\path1\Local\Programs\Python\Python311\Lib\json\encoder.py", line 258, in iterencode
    return _iterencode(o, 0)
           ^^^^^^^^^^^^^^^^^
  File "C:\Users\path\path1\Local\Programs\Python\Python311\Lib\json\encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type datetime is not JSON serializable

Now, let us move on to our tutorial.

Typeerror: object of type datetime is not json serializable – SOLUTION

Here are the solutions you can use to fix typeerror: object of type datetime is not json serializable:

1. Convert the datetime object into a string before serializing it as JSON.

To convert, use the strftime() method.

Example:

import json
from datetime import datetime

s_now = datetime.now()
s_now_str = s_now.strftime('%Y-%m-%d %H:%M:%S')

json_data = json.dumps({'timestamp': s_now_str})
print(json_data)

Output:

{"timestamp": "2023-04-12 13:41:27"}

2. Make a custom JSON encoder.

Just like above, use the strftime() method.

Example:

import json
from datetime import datetime


class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        return super(DateTimeEncoder, self).default(obj)


s_now = datetime.now()

json_data = json.dumps({'timestamp': s_now}, cls=DateTimeEncoder)
print(json_data)

Output:

{"timestamp": "2023-04-12 13:42:42"}

Tips to avoid getting Typeerrors

The following are some tips to avoid getting type errors in Python.

  • Avoid using the built-in data types in Python in the wrong way.

    → Be sure that your variables and data structures are using the correct data types.
  • Always check or confirm the types of your variables.

    → To check the types of your variables, use the type() function.

    This will allow you to confirm if the type of your variable is appropriate.
  • Be clear and concise when writing code.

    → Being clear and concise when writing your code can help you avoid typeerrors.

    It is because it will become easier to understand.
  • Handle the error by using try-except blocks.

    → Try using the try-except blocks to catch and handle any typeerror.
  • Use the built-in functions of Python if needed.

    → Use built-in functions such as int()str(), etc. if you need to convert a variable to a different type.

FAQs

What is TypeError?


Typeerror is an error in Python that arises when an operation or function is applied to a value of an improper type.

This error indicates that the data type of an object isn’t compatible with the operation or function that is being used.

What is Python?


Python is one of the most popular programming languages.

It is used for developing a wide range of applications.

In addition, Python is a high-level programming language that is used by most developers due to its flexibility.

Conclusion

In conclusion, typeerror: object of type datetime is not json serializable is an error message in Python.

It can be easily solved by converting the datetime objects into a string representation before serializing them as JSON.

That is all for this article, IT source coders!

We hope you have learned a lot from this. Have fun coding.

Thank you for reading! 😊