You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pd.to_datetime转换int64索引出现1970年代日期的问题

解决SQLite读取OHLC数据后索引转日期的问题

问题原因

  • 转成1970年代日期:你的int64索引不是秒级时间戳,大概率是毫秒(13位)或微秒(16位)级,用unit='s'会把毫秒/微秒当成秒计算,自然回到1970年 epoch 初期。
  • KeyError: 'index':df.loc['index']是按列名查找,但index是DataFrame的索引,不是普通列,所以找不到对应内容。

修复步骤

  1. 确认时间戳精度
    先打印几个索引值查看位数:

    print(df.index[:5])
    
    • 13位数字:毫秒级时间戳
    • 16位数字:微秒级时间戳
  2. 正确转换索引为datetime
    根据精度选择对应参数,加上utc=True可直接生成带+00:00的UTC时间:

    # 毫秒级时间戳转换
    df.index = pd.to_datetime(df.index, unit='ms', utc=True)
    # 微秒级时间戳转换
    df.index = pd.to_datetime(df.index, unit='us', utc=True)
    
  3. 若时间戳是普通列而非索引的情况
    如果时间戳原本是DataFrame的一列(比如列名叫timestamp),先将其设为索引再转换:

    df = df.set_index('timestamp')
    df.index = pd.to_datetime(df.index, unit='ms', utc=True)
    

内容的提问来源于stack exchange,提问作者a7dc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:40:34