如何在Polars中将整型列格式化为HH:MM:SS.0

编程语言 2026-07-11

我有一列数字,想再添加一列,把它转换成HH:MM:SS

df = pl.DataFrame({"seconds": [1.0, 4562.2, 2.44,123.567]})

我已经尝试过

df.with_columns(hhmmss=pl.struct('seconds').map_elements(lambda x: str(timedelta(seconds = str(x)))))

但都无济于事

还有其他方法吗?

解决方案

你可以使用 pl.from_epochdt.time

df.with_columns(
    hhmmss=pl.from_epoch(pl.col("seconds") * 1000, time_unit="ms").dt.time()
)

(如果你不在乎小数秒,可以省略 * 1000, time_unit="ms" 部分)

输出:

shape: (4, 2)
┌─────────┬──────────────┐
│ seconds ┆ hhmmss       │
│ ---     ┆ ---          │
│ f64     ┆ time         │
╞═════════╪══════════════╡
│ 1.0     ┆ 00:00:01     │
│ 4562.2  ┆ 01:16:02.200 │
│ 2.44    ┆ 00:00:02.440 │
│ 123.567 ┆ 00:02:03.567 │
└─────────┴──────────────┘

如果你想要以某种特定格式的字符串形式输出:

# strftime syntax: https://docs.rs/chrono/latest/chrono/format/strftime/index.html
df.with_columns(pl.col("hhmmss").dt.strftime("%H:%M:%S.%3f"))

输出:

shape: (4, 2)
┌─────────┬──────────────┐
│ seconds ┆ hhmmss       │
│ ---     ┆ ---          │
│ f64     ┆ str          │
╞═════════╪══════════════╡
│ 1.0     ┆ 00:00:01.000 │
│ 4562.2  ┆ 01:16:02.200 │
│ 2.44    ┆ 00:00:02.440 │
│ 123.567 ┆ 00:02:03.567 │
└─────────┴──────────────┘
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章