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

    dataSourceBar = {}
    dataSourceBar['chart'] = {
        "caption": "Rainfall",
            "subCaption": "Shown per date",
            "xAxisName": "Session",
            "yAxisName": "Rainfall in MM",
            "theme": "candy"
        }

    dataSourceBar['data'] = []  

    objects_with_category_id_2 = dashboard_input.objects.filter(category_category_id=2)

    for obj in objects_with_category_id_2:
        data =  {'label': obj.session_start,
                 'value': obj.input_input_value}
        dataSourceBar['data'].append(data)  

model.py

class dashboard_input(models.Model):
    session_start = models.DateTimeField(max_length=100)

traceback

Internal Server Error: /dashboard/
Traceback (most recent call last):
  File "C:UsersnatasAppDataLocalProgramsPythonPython37-32libsite-packagesdjangocorehandlersexception.py", line 34, in inner
    response = get_response(request)
  File "C:UsersnatasAppDataLocalProgramsPythonPython37-32libsite-packagesdjangocorehandlersbase.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:UsersnatasAppDataLocalProgramsPythonPython37-32libsite-packagesdjangocorehandlersbase.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:varwwwVSDKvsdkdashboardviews.py", line 69, in Chart
    return  render(request, 'dash.html', {'output' : column2D.render(),'output2' : doughnut3d.render()})
  File "C:varwwwVSDKvsdkdashboardfusioncharts.py", line 52, in render
    self.readyJson = json.dumps(self.constructorOptions, ensure_ascii=False)
  File "C:UsersnatasAppDataLocalProgramsPythonPython37-32libjson__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "C:UsersnatasAppDataLocalProgramsPythonPython37-32libjsonencoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:UsersnatasAppDataLocalProgramsPythonPython37-32libjsonencoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:UsersnatasAppDataLocalProgramsPythonPython37-32libjsonencoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type datetime is not JSON serializable

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:

for obj in objects_with_category_id_2:
        data =  {'label': str(obj.session_start),
                 'value': obj.input_input_value}
        dataSourceBar['data'].append(data) 

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

for obj in objects_with_category_id_2:
        data =  {'label': obj.session_start.isoformat(),
                 'value': obj.input_input_value}
        dataSourceBar['data'].append(data) 

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:

for obj in objects_with_category_id_2:
        data =  {'label': obj.session_start.strftime("%d.%m.%Y"),
                 'value': obj.input_input_value}
        dataSourceBar['data'].append(data) 

Good luck!

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