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

ClickHouse插入DateTime类型数据报Cannot parse expression错误怎么解决

问题根因

  • 你直接通过f-string拼接SQL插入语句,Python的datetime.now()默认输出带6位微秒的时间字符串,而你建表时指定的DateTime类型在ClickHouse中仅支持秒级精度,无法识别微秒部分导致解析失败。
  • 拼接后的SQL中时间值没有被单引号包裹,本身不符合SQL语法规范,且直接拼接SQL存在注入风险,属于不推荐的写法。

修复方案

方案1:无需保留微秒,保留原有表结构

使用clickhouse_driver官方推荐的参数绑定方式插入数据,驱动会自动完成数据类型转换,无需手动拼接:

# 替换原来的f-string插入代码
client.execute(
    'INSERT INTO crypto_exchange.historical_data_binance VALUES',
    [(
        datetime.now().replace(microsecond=0),
        datetime.now().replace(microsecond=0),
        1, 2, 3, 4, 5,
        "TYPE_K", "BTCUSDT"
    )]
)

方案2:需要保留微秒,修改表结构

先将表中两个时间字段修改为支持微秒精度的DateTime64类型:

CREATE TABLE IF NOT EXISTS historical_data_binance
(
    dateTime DateTime64(6),
    closeTime DateTime64(6),
    open Float64,
    high Float64,
    low Float64,
    close Float64,
    volume Float64,
    kline_type String,
    ticker String
) ENGINE = Memory

再用参数绑定方式插入,无需去掉微秒:

client.execute(
    'INSERT INTO crypto_exchange.historical_data_binance VALUES',
    [(datetime.now(), datetime.now(), 1, 2, 3, 4, 5, "TYPE_K", "BTCUSDT")]
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:36:00