rust 如何将日期时间序列更改为日期序列?

zlwx9yxi  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(176)
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);

datedatetime之间的date part display不相等。是否有任何方法可以获得正确的日期系列?
我看过datetime.date()函数,只解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(),
        )),
    }
}
ctehm74n

ctehm74n1#

polars tests是查找代码示例的好地方。
看起来您正在询问.strptime,它将从字符串创建一个Datetime
一旦你有了一个日期时间-你可以.cast到日期/时间对象。

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
]

相关问题