'how to display datetime list in graph using chart.js

I sent datetime values in a list from my database using python, which look like the format below. I now want to display these in a chart.

datasets: [{
               label: '# temperature',
               data: [datetime.datetime(2020, 4, 1, 9, 18, 58), datetime.datetime(2020, 4, 1, 9, 21, 1), datetime.datetime(2020, 4, 1, 10, 26, 56), datetime.datetime(2020, 4, 1, 10, 27, 9), datetime.datetime(2020, 4, 1, 10, 27, 35), datetime.datetime(2020, 4, 1, 10, 31, 6), datetime.datetime(2020, 4, 2, 17, 47, 4), datetime.datetime(2020, 4, 2, 17, 48, 18), datetime.datetime(2020, 4, 2, 17, 48, 56)]


Solution 1:[1]

You can do this using moment.js:

<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

Then in your chart script use moment() like the example below.
Please note that months are 0-indexed so you need to subtract 1 from the Python month.

<script>
    var dayFormat = 'YYYY-MM-DD hh:mm:ss';

    function newDateString(year, month, day, hour, minute, second) {
      return moment().year(year).month(month).date(day).hour(hour).minute(minute).second(second).format(dayFormat);
    };

    var data = {
        labels: [   {% for item in labels %}
                        newDateString( {{ item.year }}, 
                                       {{ item.month - 1 }}, 
                                       {{ item.day }},
                                       {{ item.hour }},
                                       {{ item.minute }},
                                       {{ item.second }}
                                     ),
                    {% endfor %}
                ],
        series: [   {% for item in series %} 
                        {{ item }},
                    {% endfor %}
                ]
    };

    var options = {
        width: "640px",
        height: "320px"
    };

    // Create a new line chart object where as first parameter we pass in a selector
    // that resolves to our chart container element. The Second parameter
    // is the actual data object.
    new Chartist.Line('#chart1', data);
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mechanical_meat