我试图在我的网络应用程序上用Highcharts stockChart显示公司历史股价的图表。股票价格数据的时间戳是从CSV文件加载的。我面临的问题是日期时间转换。在CSV文件中,每天只有5年的日期以字符串形式存在。对于这个字符串,我使用strtime()将其转换为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年的两天。 [
我猜是datetime转换成timestamp的问题。有人能帮帮我吗
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还有其他一些方法可以将datetime转换为毫秒,具体取决于您运行的python版本
成品价格数组应如下所示:
相关问题 更多 >
编程相关推荐