You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polars Duration类型转人性化字符串:默认函数是什么?能否调用?

问题解答

核心结论

Polars对pl.Duration的人性化格式化依赖内部私有函数(polars.utils.formatting._format_duration),该函数未作为公共API开放,无法直接调用。但可以通过repr()方法获取与DataFrame默认显示完全一致的格式化结果。

实现代码

修改示例代码中的格式化逻辑,替换为repr()方法:

import polars as pl

data = {"end": ["2024/11/13 10:28:00",
                "2024/10/10 10:10:10",
                "2024/09/13 09:12:29",
                "2024/08/31 14:57:02",
               ],
        "start": ["2024/11/13 10:27:33",
                  "2024/10/10 10:01:01",
                  "2024/09/13 07:07:07",
                  "2024/08/25 13:48:28",
        ]
       }

df = pl.DataFrame(data)
df = df.with_columns(
        pl.col("end").str.to_datetime(),
        pl.col("start").str.to_datetime(),
        )

df = df.with_columns(
        duration = pl.col("end") - pl.col("start"),
        )
# 替换格式化逻辑,获取和默认显示一致的字符串
df = df.with_columns(
        pl.col("duration").map_elements(lambda t: repr(t).strip("'"), return_dtype=pl.String()).alias("duration_str")
        )
print(df)

修改后输出

shape: (4, 4)
┌─────────────────────┬─────────────────────┬──────────────┬─────────────────┐
│ end                 ┆ start               ┆ duration     ┆ duration_str    │
│ ---                 ┆ ---                 ┆ ---          ┆ ---             │
│ datetime[μs]        ┆ datetime[μs]        ┆ duration[μs] ┆ str             │
╞═════════════════════╪═════════════════════╪══════════════╪═════════════════╡
│ 2024-11-13 10:28:00 ┆ 2024-11-13 10:27:33 ┆ 27s          ┆ 27s             │
│ 2024-10-10 10:10:10 ┆ 2024-10-10 10:01:01 ┆ 9m 9s        ┆ 9m 9s           │
│ 2024-09-13 09:12:29 ┆ 2024-09-13 07:07:07 ┆ 2h 5m 22s    ┆ 2h 5m 22s       │
│ 2024-08-31 14:57:02 ┆ 2024-08-25 13:48:28 ┆ 6d 1h 8m 34s ┆ 6d 1h 8m 34s    │
└─────────────────────┴─────────────────────┴──────────────┴─────────────────┘

补充说明

  • repr()返回的字符串默认带有单引号,因此需要用strip("'")去除多余符号。
  • 不建议直接调用内部私有函数(如_format_duration),这类函数不受版本兼容性保障,可能在Polars迭代中被修改或移除。

内容的提问来源于stack exchange,提问作者Yves Dorfsman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:45:54