如何在 Rust 中使用极地日期?

Kus*_*esh 5 rust rust-polars

我正在使用 LazyCsvReader 读取文件,并且该文件包含日期列。LazyCsvReader 将日期读取为字符串。日期的格式为“%m-%d-%Y”。如何正确处理日期。有一个页面是针对这个的,但它是针对 python 的。我试图阅读文档但无法弄清楚。以下是我的尝试案例,但无法编译

use polars::prelude::*;
use polars_lazy::prelude::*;
use chrono::prelude::*;
use polars_core::time::*;

fn main() {
    let lf = read_csv_lazy("file.csv").unwrap();
    let out = lf.clone()
    .with_column((col("InvoiceDate").utf8().strptime("%m-%d-%Y")))
    .collect();
    println!("{:?}", out3);
}
fn read_csv_lazy(file_name: &str) -> Result<LazyFrame> {
    let lf: LazyFrame = LazyCsvReader::new(file_name.into())
                    .has_header(true)
                    .with_encoding(CsvEncoding::LossyUtf8)
                    .finish()?;
    Ok(lf)
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

error[E0599]: no method named `utf8` found for enum `Expr` in the current scope
  --> src/main.rs:20:38
   |
20 |     .with_column((col("InvoiceDate").utf8().strptime("%m-%d-%Y")))
   |                                      ^^^^ method not found in `Expr`
Run Code Online (Sandbox Code Playgroud)

rit*_*e46 6

极地Expressions不能向下转型,除非您mapapply关闭底层Series

但是,在这种情况下,您不需要任何关闭。您可以使用方法str下可用的命名空间Expr::str()

let options = StrpTimeOptions {
    fmt: Some("%m-%d-%Y".into()),
    ..Default::default()
};


let my_expr = col("InvoiceDate").str().strptime(options);
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我想通了。我需要在 Cargo.toml 文件中添加 Polars = {version="0.21.1", features = ["strings"]} 。并写入 ``` let options = StrpTimeOptions { fmt: Some("%Y/%m/%d".into()), date_dtype: DataType::Date, ..Default::default() }; ``感谢您的帮助@ritchie46。 (3认同)