1
let datetime = frame.column("datetime_nano")?.cast(&DataType::Datetime(TimeUnit::Nanoseconds, None))?;
let date = datetime.cast(&DataType::Date)?;
let time = datetime.cast(&DataType::Time)?;
println!("{}", datetime);
println!("{}", date);

The date part display between date and datetime is not equal. Is there any way to get the correct date series ?

I have read the datetime.date() function. just only solve dtype == DateType::Date.

#[cfg(feature = "dtype-date")]
pub fn date(&self) -> PolarsResult<&DateChunked> {
    match self.dtype() {
        DataType::Date => unsafe {
            Ok(&*(self.as_ref() as *const dyn SeriesTrait as *const DateChunked))
        },
        dt => Err(PolarsError::SchemaMisMatch(
            format!("Series of dtype: {dt:?} != Date").into(),
        )),
    }
}
somewheve
  • 125
  • 6
  • If you could add an example df (even 1 row) to show the input along with the output you get, and the output you expect - it would help. – jqurious Feb 01 '23 at 08:18

1 Answers1

1

The polars tests are a good place to look for code examples.

It looks like you're asking about .strptime which will create a Datetime from a string.

Once you have a Datetime - you can .cast to Date / Time objects.

use polars::prelude::*;

fn main() -> PolarsResult<()> {
    let frame = df!("datetime_nano" => ["2019-03-22T14:00:01.700311864"])?
        .lazy()
        .with_column(col("datetime_nano").str().strptime(StrpTimeOptions {
            date_dtype: DataType::Datetime(TimeUnit::Nanoseconds, None),
            ..Default::default()
        }))
        .collect()?;

    let datetime = frame.column("datetime_nano")?;
    let date = datetime.cast(&DataType::Date)?;
    let time = datetime.cast(&DataType::Time)?;

    println!("{:?}", frame);
    println!("{:?}", datetime);
    println!("{:?}", date);
    println!("{:?}", time);

    Ok(())
}
shape: (1, 1)
┌───────────────────────────────┐
│ datetime_nano                 │
│ ---                           │
│ datetime[ns]                  │
╞═══════════════════════════════╡
│ 2019-03-22 14:00:01.700311864 │
└───────────────────────────────┘
shape: (1,)
Series: 'datetime_nano' [datetime[ns]]
[
    2019-03-22 14:00:01.700311864
]
shape: (1,)
Series: 'datetime_nano' [date]
[
    2019-03-22
]
shape: (1,)
Series: 'datetime_nano' [time]
[
    14:00:01.700311864
]
jqurious
  • 9,953
  • 1
  • 4
  • 14
  • ``` let datetime = frame.column("datetime_nano")?.cast(&DataType::Datetime(TimeUnit::Nanoseconds, Some("Asia/Shanghai".to_string())))?; ``` worked, and thanks for your look.... I positioned the problem wrong – somewheve Feb 01 '23 at 10:15