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`
Kushdesh
  • 1,118
  • 10
  • 16

1 Answers1

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);
ritchie46
  • 10,405
  • 1
  • 24
  • 43
  • 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. – Kushdesh May 21 '22 at 14:13
  • 3
    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. – Kushdesh May 22 '22 at 13:18
  • 1
    @richie46 Is there way to convert it back to some date format? Any format would do. using date() function on chunkedarray create i32 values. – Kushdesh Jun 05 '22 at 12:17