从CSV文件到在Highstock JS中绘图的数据时间错误

时间:2019-03-26 07:30:01

标签: python datetime highcharts timestamp

我正在尝试使用Highcharts stockChart在我的Web应用程序上显示公司的历史股价图。正在从CSV文件加载带有股票价格数据的时间戳。我面临的问题是日期时间转换。在CSV文件中,只有每天5年的字符串形式的日期。这个字符串,我正在使用strptime()转换为datetime对象,并将其转换为时间戳,以作为参数发送给javascript中的stockChart。但是问题是这样的-CSV文件的每日日期为2014-2019,但是在图表中,转换后的日期仅在1970年显示了两天。

我认为这可能是与时区有关的转换问题。

Python后端代码(Django views.py函数)

csvFile = company + ".csv"

        file = open(csvFile)
        reader = csv.reader(file)
        data = list(reader)
        prices = []
        for row in data:
            temp = []
            temp.append(datetime.timestamp(datetime.strptime((row[0]) + " 09:30:00 +0000", '%Y-%m-%d %H:%M:%S %z')))
            temp.append(float(row[1]))
            prices.append(temp)

        arg = {'symbol':company, 'prices':prices}
        return render(request, 'history.html', arg)

JavaScript代码

<script type="text/javascript">

// Create the chart
Highcharts.stockChart('container', {

  time: {
    useUTC: false
  },

  rangeSelector: {
    buttons: [{
      count: 7,
      type: 'day',
      text: '1W'
    }, {
      count: 1,
      type: 'month',
      text: '1M'
    }, {
      count: 6,
      type: 'month',
      text: '6M'
    }, {
      count: 1,
      type: 'year',
      text: '1Y'
    }, {
      count: 2,
      type: 'year',
      text: '2Y'
    }, {
      type: 'all',
      text: 'All'
    }],
    inputEnabled: true,
    selected: 1
  },

  title: {
    text: 'Historical Stock prices'
  },

  exporting: {
    enabled: true
  },

  series: [{
    name: "{{ symbol }}",
    data: {{ prices }},
    tooltip: {
                valueDecimals: 2
            }
  }]
});

</script>

CSV文件的日期为2014-2019 [CSV file[1

但是在该图中,仅显示了1970年的两天。 [But the graph shows only 1970 year[2

我猜想它是将日期时间转换为时间戳的问题。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

Highcharts使用1970年以来以毫秒为单位的时间作为唯一的日期时间单位。

这意味着您的代码

datetime.timestamp(datetime.strptime((row[0]) + " 09:30:00 +0000", '%Y-%m-%d %H:%M:%S %z'))

需要返回毫秒,而不是 seconds

最简单的解决方法是:

datetime.timestamp(datetime.strptime((row[0]) + " 09:30:00 +0000", '%Y-%m-%d %H:%M:%S %z'))*1000

This answer还有其他一些方法可以根据您所运行的python版本将日期时间转换为毫秒。

您的成品价格数组应如下所示:

[
  [1553588587236, 38.84],
  [1553588588236, 31.31],
  ...
]