Skip to content
Advertisement

Object of type datetime is not JSON serializable error

I have some issues with using a DateTime value in python. When I use session_start in the following code, I get an Object of type datetime is not JSON serializable error

views.py

JavaScript

model.py

JavaScript

traceback

JavaScript

I retrieve the value from a database view which is filled by other tables where the user fills in their data.

Could someone help me with this?

Advertisement

Answer

As the error message says, datetime objects cannot be converted by json automatically to a string or a dictionary. It seems your view function is converting everything to json before sending it to the front end, or to rendering.

All you need to do is to explicitly convert the DateTime object to a string for your code to work:

JavaScript

Or use the built in functions from datetime to format it. For ISO Format use .isoformat():

JavaScript

If you want the date to have a different format, you can use the datetime.strftime(format) function, that takes a string containing the format of the resulting date string. Check the datetime package documentation: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

maybe something like this:

JavaScript

Good luck!

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement