Search code examples
rustrust-polars

How to use date in polars in rust?


I am reading file using LazyCsvReader and the file contains a date column. LazyCsvReader read the date as string. The date is in format "%m-%d-%Y". How to properly handle it as date. There is a page for this but it is for python. I tried to read the documentation but couldn't figure it out. Following is my try case which doesn't compile

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)
}

I am getting following error

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`

Solution

  • Polars Expressions cannot be downcasted unless you map or apply a closure over the underlying Series.

    However, in this case you don't need any closure. You can use the str namespace, available under the Expr::str() method.

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