【问题标题】:Datatime from CSV file to plot in Highstock JS error从 CSV 文件到在 Highstock JS 错误中绘制的日期时间
【发布时间】:2019-03-26 07:30:01
【问题描述】:

我正在尝试使用 Highcharts stockChart 在我的网络应用程序上显示公司的历史股价图表。正在从 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 [

但在图表中,仅显示了 1970 年的两天。 [

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

【问题讨论】:

    标签: python datetime highcharts timestamp


    【解决方案1】:

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

    这意味着你的代码

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

    需要返回 毫秒,而不是

    最简单的解决方法是:

    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],
      ...
    ]
    

    【讨论】:

    • 哦,好的,知道了。非常感谢!
    猜你喜欢
    • 2016-07-25
    • 1970-01-01
    • 2016-05-15
    • 2021-12-24
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多