Polars时长类型在电子表格中的理想存储方式咨询
Polars Duration 导出至电子表格的理想存储方案
针对Polars的duration类型导出到电子表格时自动转换的问题,有两种理想的存储方式,可根据需求选择:
一、转换为自定义显示字符串(适合仅展示场景)
直接将duration格式化为你需要的“1d 2m”“2h 1m”样式字符串,导出后电子表格会原样保留文本,不会自动转换。通过Polars表达式拼接各时间分量即可实现:
import polars as pl # 示例DataFrame df = pl.DataFrame({ "duration": [pl.duration(days=1, minutes=2), pl.duration(hours=2, minutes=1)] }) # 生成自定义格式字符串 df = df.with_columns( formatted_duration=pl.when(pl.col("duration").dt.days() > 0) .then(pl.col("duration").dt.days().cast(str) + "d ") .otherwise("") + pl.when(pl.col("duration").dt.hours() > 0) .then(pl.col("duration").dt.hours().cast(str) + "h ") .otherwise("") + pl.col("duration").dt.minutes().cast(str) + "m" .str.strip() # 去除首尾空格 )
这种方式的缺点是字符串无法直接参与时间计算,仅适合纯展示需求。
二、转换为ISO 8601标准时间间隔格式(适合需计算场景)
将duration转为ISO 8601标准的时间间隔格式(如P1DT2M对应1天2分钟,PT2H1M对应2小时1分钟),这种格式是电子表格(如Excel)可识别的结构化时间间隔类型,既能保留计算能力,又不会在导出时被乱转:
df = df.with_columns( iso_duration=pl.col("duration").dt.to_string(format="%P") )
导出后,电子表格能正确解析为时间间隔,支持后续的加减等计算操作,适合需要对数据做进一步处理的场景。
内容的提问来源于stack exchange,提问作者apostofes
相关产品推荐
相关产品推荐

