how to send datetime dataframe to django template and plot it in js using plotly

痞子三分冷 提交于 2021-01-05 07:09:30

问题


I have a data-frame and I want to send it in my Django template.

dummy code in views.py:

def graphs(request):

    df_new = pd.read_excel("/home/cms/cms/static/Sensorik.xlsx")

    times = df_new.loc[:, df_new.columns[0]].to_json(orient='records') 
    # columns[0] contains datetime values
    
    data_color = df_georgian.loc[:, df_georgian.columns[2]]
    color = data_color.to_json(orient='records')

    context = {
        'times': times,
        'data_color': color,
        ...
        }
    return render(request, 'graphs/graphs.html', context)

In my template, I get these data like the following:

<script>
    var times = {{ times|safe }};
    console.log('index: ', typeof(index));
    var color = {{ data_color|safe }};
</script>

the color variable is totally ok but the times variable when get to JSON format turns from 2018-05-29 08:09:00 format to something like it:

element: 1528108200000

I want to be able to plot the color based on times to get a line graph with plotly. i.e. I want to show times as x-ticks of my plot.

any suggeston on

1- how to send datetime dataframe to django template?

or

2- how to convert element: 1528108200000 into a datetime in js to plot it as x-ticks?


回答1:


Whenever you see something that should be a date or time expressed in a large number like the 1528108200000 format, that means it is or is similar to a UNIX timestamp—the number of seconds past January 1, 1970. In this case, the length of the timestamp indicates that it's milliseconds, not seconds, so it's not exactly a UNIX timestamp but is very close.

Milliseconds since January 1, 1970 is the way that JS internally stores Date objects, which is interesting because it means some sort of conversion is probably happening on the JS side, not the python side (where you'd usually get ISO format or UNIX Timestamps).

In any case, it's pretty easy to solve on the JS side because you can simply parse the number:

dateObject = new Date(1528108200000);

If you do that parsing and pass the data to Plotly as Date objects, Plotly should be able to recognize your dates.

A simple way to do that would be:

const times = [1528108200000, 1528108200000, 1528108200000]
const parsed = times.map(time => new Date(time))

assuming your times variable is just an array of these integers.



来源:https://stackoverflow.com/questions/65335321/how-to-send-datetime-dataframe-to-django-template-and-plot-it-in-js-using-plotly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!