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

Rust Polars字符串转Datetime失败:t_hour列全为null的解决咨询

Rust Polars字符串转Datetime全为null的问题解决

问题场景

执行以下代码将字符串列hour转为Datetime类型时,结果列t_hour全部为null:

let t_hour_df = hour_df.clone().lazy()
        .with_column(
            col("hour").cast(DataType::Datetime(TimeUnit::Nanoseconds, Some(PlSmallStr::from("%Y-%m-%d %H%M")))).alias("t_hour")
        )
        .collect()
        .unwrap();
println!("{:?}",&t_hour_df);

输出结果:

┌────┬──────────┬──────────────┐
│ code      ┆ hour                             ┆ t_hour                                          │
│ ---          ┆ ---                                ┆ ---                                                 │
│ str          ┆ str                                 ┆ datetime[ns]                               │
╞════╪══════════╪══════════════╡
│ 000017  ┆ 2025-01-15 1030          ┆ null                                              │
│ 000017 ┆ 2025-01-15 1130           ┆ null                                              │
│ 000017 ┆ 2025-01-15 1400           ┆ null                                              │
│ 000017 ┆ 2025-01-15 1500           ┆ null                                              │

调试后确认,hour列的字符串实际包含双引号(如"2025-01-15 1030"),但直接打印DataFrame时未显示该引号。

失败原因

指定的日期格式串%Y-%m-%d %H%M与实际字符串不匹配——实际字符串首尾带有双引号,而格式串未对应处理,导致Polars无法解析该字符串为Datetime类型,最终返回null。

解决方法

方法1:先去除字符串中的双引号

在类型转换前,使用Polars的字符串操作去除首尾双引号:

let t_hour_df = hour_df.clone().lazy()
        .with_column(
            col("hour")
                .str.strip_chars('"') // 去除首尾双引号
                .cast(DataType::Datetime(TimeUnit::Nanoseconds, Some(PlSmallStr::from("%Y-%m-%d %H%M"))))
                .alias("t_hour")
        )
        .collect()
        .unwrap();

方法2:修改格式串匹配带引号的字符串

调整日期格式串,将首尾的双引号包含进去(注意转义):

let t_hour_df = hour_df.clone().lazy()
        .with_column(
            col("hour")
                .cast(DataType::Datetime(TimeUnit::Nanoseconds, Some(PlSmallStr::from("\"%Y-%m-%d %H%M\"")))) // 格式串包含双引号
                .alias("t_hour")
        )
        .collect()
        .unwrap();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 08:28:18