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

解决pandas Timestamp适配peewee DateTimeField的批量插入问题

解决Pandas Timestamp转Peewee DateTimeField批量插入SQLite的问题

问题场景

需要通过pandas.to_dict()将DataFrame转换为字典,再用peewee.insert_many()批量插入SQLite数据库。核心要求是把Pandas的Timestamp类型转换为兼容PeeweeDateTimeField的格式,但:

  • 不想转成datetime.date(),不符合业务需求
  • 不想用to_json(),会把Timestamp转为整数时间戳,不希望以整数格式存储日期

无效尝试

使用to_pydatetime()转换后,结果仍为Timestamp类型,执行插入时触发InterfaceError,提示参数类型不支持。

可行解决方案

发现Peewee的DateTimeField支持字符串格式的时间,将Timestamp列转为字符串后再转字典插入,既满足存储格式要求,效率也很高,适合处理数万行数据:

# 将Timestamp列转为字符串格式
hdf.time = hdf.time.astype(str)
# 转换为records格式的字典列表
hdf_dict = hdf.to_dict(orient="records")
# 执行批量插入
db.Candles1Minute.insert_many(hdf_dict).execute()

对应Peewee模型定义

class Candles1Minute(BaseModel):
    symbol = TextField()
    time = DateTimeField()
    open = FloatField()
    high = FloatField()
    low = FloatField()
    close = FloatField()
    volume = IntegerField(null=True)

    class Meta:
        indexes = ((("symbol", "time"), True),)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:01:05