问题描述
我正在从在UNIX毫秒时间内加上时间戳的API检索数据,并试图将这些数据保存到CSV文件中。数据以每日间隔为单位,但如上所述,以UNIX毫秒表示。
我正在使用pandas函数将毫秒转换为日期时间,但仍未将数据与日时间一起保存。我的代码如下:
ticker = 'tBTCUSD'
r = requests.get(url,params = params)
data = pd.DataFrame(r.json())
data.set_index([0],inplace = True)
data.index = pd.to_datetime(data.index,unit = 'ms' )
data.to_csv('bitfinex_{}_usd_{}.csv'.format(ticker[1:-3].lower(),'1D'),mode='a',header=False)
它将数据另存为2020-08-21
,而不是2020-08-21 00:00:00
。当我按小时或15分钟轮询API时,该时间仍然包含时间,但每天却没有。我想知道是否缺少将步骤从UNIX毫秒转换为%Y-%m-%d %H:%M:%S %Z
格式的步骤?
解决方法
您始终可以明确指定格式:
data.index = pd.to_datetime(data.index,unit='ms').strftime('%Y-%m-%d %H:%M:%S UTC')
print(data)
1 2 3 4 5
0
2020-09-10 00:00:00 UTC 10241.000000 10333.862868 10516.00000 10233.087967 3427.178984
2020-09-09 00:00:00 UTC 10150.000000 10240.000000 10359.00000 10010.000000 2406.147398
2020-09-08 00:00:00 UTC 10400.000000 10148.000000 10464.00000 9882.400000 6761.138356
2020-09-07 00:00:00 UTC 10275.967600 10397.000000 10430.00000 9913.800000 6301.951492
2020-09-06 00:00:00 UTC 10197.000000 10276.000000 10365.07422 10031.000000 2755.663001
... ... ... ... ... ...
2020-05-18 00:00:00 UTC 9668.200000 9714.825163 9944.00000 9450.000000 9201.536549
2020-05-17 00:00:00 UTC 9386.000000 9668.200000 9883.50000 9329.700000 9663.262087
2020-05-16 00:00:00 UTC 9307.600000 9387.952090 9580.00000 9222.000000 4157.691762
2020-05-15 00:00:00 UTC 9791.000000 9311.200000 9848.90000 9130.200000 11340.269781
2020-05-14 00:00:00 UTC 9311.967387 9790.954158 9938.70000 9266.200000 12867.687617