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

Rust Polars如何将字符串列转换为DateTime类型

在Rust Polars中实现字符串转DateTime的方法

对应Python代码的Rust实现步骤

先看完整示例代码,再拆解关键逻辑:

use polars::prelude::*;
use chrono::format::strftime::StrftimeItems;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 读取目标CSV文件
    let mut df = CsvReader::from_path("your_file.csv")?
        .finish()?;

    // 1. 移除"Meetdatum"列中的所有点号,对应Python的str.replace操作
    df = df.with_column(
        col("Meetdatum")
            .str()
            .replace(".", "", false) // false表示禁用正则,做普通字符串替换
            .alias("Meetdatum_cleaned")
    )?;

    // 2. 将清理后的字符串转换为DateTime类型,对应pd.to_datetime
    df = df.with_column(
        col("Meetdatum_cleaned")
            .str()
            .strptime(
                DataType::Datetime(TimeUnit::Milliseconds, None),
                StrftimeItems::new("%d %b %Y"),
                // 配置解析选项:非严格模式+完全匹配格式
                Some(StrptimeOptions {
                    strict: false,
                    exact: true,
                    ..Default::default()
                })
            )
            .alias("Datum")
    )?;

    // 可选:移除临时生成的中间列
    df = df.drop("Meetdatum_cleaned")?;

    println!("{:?}", df);
    Ok(())
}

关键细节说明

  1. 依赖配置
    需要在Cargo.toml中添加必要依赖:

    [dependencies]
    polars = { version = "0.32.0", features = ["csv", "str", "datetime"] }
    chrono = "0.4.31"
    

    其中csv、str、datetime是Polars的功能特性,按需启用。

  2. 字符串替换逻辑

    • col("Meetdatum").str():将列转换为字符串处理上下文
    • replace(".", "", false):第三个参数false对应Python的regex=False,执行普通字符串替换而非正则匹配。
  3. DateTime转换逻辑

    • strptime方法需要三个核心参数:
      1. 目标数据类型:DataType::Datetime(TimeUnit::Milliseconds, None)指定毫秒精度的DateTime,可根据需求改为Seconds或Microseconds
      2. 格式解析器:StrftimeItems::new("%d %b %Y")对应Python的format="%d %b %Y",注意格式符要和字符串完全匹配(比如%b是英文月份缩写)
      3. 解析选项:StrptimeOptions用于处理解析容错,strict: false允许忽略大小写等细微差异,exact: true要求字符串完全匹配格式,避免歧义。

注意事项

  • 如果原始列存在缺失值,Polars会自动将解析失败或缺失的行标记为None(对应DateTime列的空值)
  • 若格式符不匹配会导致解析错误,可通过调整strict参数或检查格式字符串解决
  • 若不需要保留原始的Meetdatum列,可以直接在替换后原地转换,无需生成中间列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:35:29