1

I am reading a datatimes objects and want to send them to chart.js chart as x-axis. These are np.datatime64 objects. What is the best way to send it? In my page I have got:

@app.route('/chart')
def chart():
    x = [str(d) for d in dataframe["Date"].values] # these are datetimes - here I just do str()
    y = [v for v in dataframe["Value"].values] # these are floats

    return render_template('chart.html', labels=x, values=y)

In chart.html:

<body>
    <script type="text/javascript">
      {% include "mychart.js" %}
    </script>
</head>
<body>
    <div class="container">
        <canvas id="myChart" width="1500" height="500"></canvas>
    </div>
</body>

And in mychart.js:

window.onload = function() {
var chartData = {
  labels : [{% for d in labels %} new Date("{{d}}"), {% endfor %}],  // or {{d|tojson }}
  datasets : [{
      fill: true,
      lineTension: 0.1,
      backgroundColor: "rgba(75,192,192,0.4)",
      borderColor: "rgba(75,192,192,1)",
      data : [{% for item in values %} {{item}},{% endfor %}],
      spanGaps: false
  }]
}

var ctx = document.getElementById("myChart").getContext("2d");

var myChart = new Chart(ctx, {
  type: 'line',
  data: chartData,
});
}

And json.dump or jsonfy do not serialize np.datetime64 objects.

I cannot do

x = [json.dump(d) for d in dataframe["Date"].values]

becuase it raises exception that it cannot be serialized

TypeError: Object of type 'datetime64' is not JSON serializable

I think that these object have no "isoformat()" method so only way is to make them strings?

0 Answers0