如何在Polars(Rust)中将Duration格式化为HH:MM:SS格式?
在Polars(Rust)中将Duration格式化为HH:MM:SS格式
Polars目前没有直接内置的Duration格式化函数来输出HH:MM:SS格式,你可以通过计算总秒数拆分出时、分、秒,再拼接成目标格式,具体实现如下:
修改后的完整代码
use polars::prelude::*; fn main() { let df = df! { "a" => ["2022-11-21T12:00:00"], "b" => ["2022-11-21T14:00:00"] } .unwrap() .lazy() // 解析字符串为datetime类型 .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"), ) // 计算时间差得到duration .with_column((col("b") - col("a")).alias("duration")) // 格式化duration为HH:MM:SS .with_column( (col("duration").cast(DataType::Int64) / lit(1000)) .alias("total_secs") ) .with_column( (col("total_secs") / lit(3600)) .cast(DataType::Utf8) .str() .zfill(2) .alias("hours") ) .with_column( (col("total_secs") % lit(3600)) .alias("remaining_secs") ) .with_column( (col("remaining_secs") / lit(60)) .cast(DataType::Utf8) .str() .zfill(2) .alias("mins") ) .with_column( (col("remaining_secs") % lit(60)) .cast(DataType::Utf8) .str() .zfill(2) .alias("secs") ) // 拼接成HH:MM:SS格式 .with_column( col("hours") .concat(lit(":")) .concat(col("mins")) .concat(lit(":")) .concat(col("secs")) .alias("duration_formatted") ) // 移除中间计算列 .drop_columns(&["total_secs", "hours", "remaining_secs", "mins", "secs"]) .collect() .unwrap(); println!("{:?}", df); }
代码说明
- 转换总秒数:将
duration[ms]类型转为整数(毫秒数)后除以1000,得到总秒数 - 拆分时、分、秒:
- 小时 = 总秒数 ÷ 3600
- 剩余秒数 = 总秒数 % 3600
- 分钟 = 剩余秒数 ÷ 60
- 秒 = 剩余秒数 % 60
- 补零与拼接:用
str().zfill(2)确保每个部分都是两位数字,再通过concat拼接成HH:MM:SS格式 - 清理中间列:最后移除用于计算的临时列,只保留核心结果
运行结果
┌─────────────────────┬─────────────────────┬──────────────┬──────────────────┐ │ a ┆ b ┆ duration ┆ duration_formatted │ │ --- ┆ --- ┆ --- ┆ --- │ │ datetime[ms] ┆ datetime[ms] ┆ duration[ms] ┆ str │ ╞═════════════════════╪═════════════════════╪══════════════╪══════════════════╡ │ 2022-11-21 12:00:00 ┆ 2022-11-21 14:00:00 ┆ 2h ┆ 02:00:00 │ └─────────────────────┴─────────────────────┴──────────────┴──────────────────┘
内容的提问来源于stack exchange,提问作者ohe
相关产品推荐
相关产品推荐

