【问题标题】:Pandas dataframe not including time of day when converting from UNIX从 UNIX 转换时,Pandas 数据帧不包括一天中的时间
【发布时间】:2020-12-29 09:00:55
【问题描述】:

我正在从一个以 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 格式的步骤?

【问题讨论】:

  • 网址是什么?
  • url = 'api.bitfinex.com/v2/candles/trade:{}:{}/hist'.format('1D',ticker)
  • 参数呢?
  • start_date = int(time.mktime(dt.strptime('2016-01-01 00:00:00 UTC', '%Y-%m-%d %H:%M:%S %Z').timetuple()) * 1000) end_date = int(time.mktime(dt.strptime('2020-09-01 00:00:00 UTC', '%Y-%m-%d %H:%M:%S %Z').timetuple()) * 1000)params = { 'start': start_date, 'end': end_date, 'sort': 1, 'limit' : 10000}

标签: python pandas datetime time strftime


【解决方案1】:

您始终可以明确指定格式:

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

【讨论】:

  • 我怎样才能让它同时显示 UTC 时区?
  • 你的意思是DataFrame本身?
  • 是的,所以它就是这样存储的。
猜你喜欢
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 2013-04-23
  • 2013-10-14
相关资源
最近更新 更多