如何将持续时间格式化为HH:MM:SS格式?
作为测试样本,我有
fn main() {
let df = df! {
"a" => ["2022-11-21T12:00:00"],
"b" => ["2022-11-21T14:00:00"]
}
.unwrap()
.lazy()
.with_column(
col("a")
.str()
.strptime(StrpTimeOptions {
date_dtype: DataType::Datetime(TimeUnit::Milliseconds, None),
fmt: Some("%Y-%m-%dT%H:%M:%S".into()),
strict: false,
exact: true,
})
.alias("a"),
)
.with_column(
col("b")
.str()
.strptime(StrpTimeOptions {
date_dtype: DataType::Datetime(TimeUnit::Milliseconds, None),
fmt: Some("%Y-%m-%dT%H:%M:%S".into()),
strict: false,
exact: true,
})
.alias("b"),
)
.with_column((col("b") - col("a")).alias("duration"))
.collect()
.unwrap();
println!("{:?}", df);
}It输出
┌─────────────────────┬─────────────────────┬──────────────┐
│ a ┆ b ┆ duration │
│ --- ┆ --- ┆ --- │
│ datetime[ms] ┆ datetime[ms] ┆ duration[ms] │
╞═════════════════════╪═════════════════════╪══════════════╡
│ 2022-11-21 12:00:00 ┆ 2022-11-21 14:00:00 ┆ 2h │
└─────────────────────┴─────────────────────┴──────────────┘在前面的示例中,如何将持续时间转换为"02:00:00“?
发布于 2022-11-21 17:56:02
不幸的是,我不认为你能做得比这更好(但我希望被证明是错的)。
.with_column(
col("duration")
.map(
|srs| {
Ok(srs
.duration()?
.into_iter()
.map(|d| {
d.map(|millisecs| {
let secs = millisecs / 1000;
let h = secs / (60 * 60);
let m = (secs / 60) % 60;
let s = secs % 60;
format!("{}:{:0<2}:{:0<2}", h, m, s)
})
})
.collect::<Utf8Chunked>()
.into_series())
},
GetOutput::from_type(DataType::Utf8),
)
.alias("duration_str"),
)这将导致2:00:00。它是硬编码的,您处理的是毫秒;您可能需要将一个变量存储在TimeUnit中,然后切换它来确定分母,而不是总是使用1000。
https://stackoverflow.com/questions/74522375
复制相似问题