Object of type datetime is not JSON serializable error

17,485

Solution 1

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!

Solution 2

In your code, you have a Datetime field on the model. When you reference that it's a datetime object, which, as the error says, is not serializable.

You can get around this by explicitly casting it to a string, like so:

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

I don't know what type the `obj.input_input_value will be, but you may or may not have to cast that too. Try without first and see if this works for you.

Share:
17,485

Related videos on Youtube

Natasja
Author by

Natasja

Updated on September 17, 2022

Comments

  • Natasja
    Natasja over 1 year

    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:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "C:\var\www\VSDK\vsdk\dashboard\views.py", line 69, in Chart
        return  render(request, 'dash.html', {'output' : column2D.render(),'output2' : doughnut3d.render()})
      File "C:\var\www\VSDK\vsdk\dashboard\fusioncharts.py", line 52, in render
        self.readyJson = json.dumps(self.constructorOptions, ensure_ascii=False)
      File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
        **kw).encode(obj)
      File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 199, in encode
        chunks = self.iterencode(o, _one_shot=True)
      File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 257, in iterencode
        return _iterencode(o, 0)
      File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.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?

  • Natasja
    Natasja almost 5 years
    Thank you! I was trying to fix it with way more complicated code, but it was way easier than I thought!
  • Natasja
    Natasja almost 5 years
    Thank you! It was easier than I thought :)
  • Mohammed Baashar
    Mohammed Baashar over 4 years
    splendid; I used the built-in to "ISO" function