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

如何用polars::LazyFrame和Datatype::Datetime计算时长?解决AsRef<[Expr]>报错

解决Polars LazyFrame计算时间差的报错问题

错误原因

你触发的特征‘AsRef<[Expr]>’未为‘Expr’实现错误,是因为with_columns方法要求传入表达式集合(比如Vec<Expr>或&[Expr]切片),但你直接传入了单个Expr,不符合方法的参数类型要求。

两种修正方案

方案1:使用with_column(单数方法)

如果你只需要新增一列时间差计算结果,直接用接受单个Expr的with_column方法更贴合场景:

let data: LazyFrame = read_data(name)
    .unwrap()
    .with_column(col("updatedAt").cast(DataType::Datetime(TimeUnit::Milliseconds, None)))
    .with_column(col("createdAt").cast(DataType::Datetime(TimeUnit::Milliseconds, None)))
    // 用with_column(单数)传入单个Expr,同时用alias给列命名
    .with_column(
        col("updatedAt")
            .sub(col("createdAt"))
            .dt()
            .total_seconds()
            .alias("duration_seconds")
    );
let data2 = data.collect().unwrap();

方案2:调整参数适配with_columns(复数方法)

如果后续需要批量新增多列,保持用with_columns,但要把单个Expr放到数组或Vec中传入:

let data: LazyFrame = read_data(name)
    .unwrap()
    .with_column(col("updatedAt").cast(DataType::Datetime(TimeUnit::Milliseconds, None)))
    .with_column(col("createdAt").cast(DataType::Datetime(TimeUnit::Milliseconds, None)))
    // 用数组包裹单个Expr,满足AsRef<[Expr]>的要求
    .with_columns([
        col("updatedAt")
            .sub(col("createdAt"))
            .dt()
            .total_seconds()
            .alias("duration_seconds")
    ]);
let data2 = data.collect().unwrap();

额外说明

  • dt().total_seconds()会将时间差转换为秒数的浮点值,适合后续数值计算;
  • 用alias给计算列命名,避免默认生成的冗长列名,方便后续数据引用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 18:40:14