How to use date in polars in rust?
Asked Answered
D

1

5

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`
Dissatisfied answered 17/5, 2022 at 15:26 Comment(0)
B
6

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);
Bandanna answered 21/5, 2022 at 9:10 Comment(3)
I edited my code to .with_column((col("InvoiceDate").str().strptime(options))) . Now the error says: error[E0599]: no method named str found for enum Expr in the current scope.Dissatisfied
Okay I figured it out. I need to add polars = {version="0.21.1", features = ["strings"]} in Cargo.toml file. And write ``` let options = StrpTimeOptions { fmt: Some("%Y/%m/%d".into()), date_dtype: DataType::Date, ..Default::default() }; ``` Thanks for your help @ritchie46.Dissatisfied
@richie46 Is there way to convert it back to some date format? Any format would do. using date() function on chunkedarray create i32 values.Dissatisfied

© 2022 - 2025 — McMap. All rights reserved.