如何在Polars中按自定义时间精度将时间间隔转换为数值?
在Polars中高效转换时间间隔为指定精度的数值
Polars提供了内置的Duration方法,可以直接按指定精度将时间间隔转换为数值,比手动计算更简洁且不易出错。下面针对你的场景给出优化实现:
优化后的实现代码
import polars as pl df = pl.DataFrame({ "from": ["2023-01-01", "2023-01-02", "2023-01-03"], "to": ["2023-01-04", "2023-01-05", "2023-01-06"], }) # 一步完成日期转换、时间差计算与数值转换 df = df.with_columns( pl.col("to").str.to_date() - pl.col("from").str.to_date() ).with_columns( # 直接用dt.total_days()获取天数,再转为整数 pl.col("to").str.to_date().sub(pl.col("from").str.to_date()).dt.total_days().cast(pl.Int8).alias("time_diff_days"), # 如需其他精度,比如小时 pl.col("to").str.to_date().sub(pl.col("from").str.to_date()).dt.total_hours().cast(pl.Int32).alias("time_diff_hours") ) print(df)
输出结果
shape: (3, 4) ┌────────────┬────────────┬───────────────┬────────────────┐ │ from ┆ to ┆ time_diff_days ┆ time_diff_hours │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i8 ┆ i32 │ ╞════════════╪════════════╪═══════════════╪════════════════╡ │ 2023-01-01 ┆ 2023-01-04 ┆ 3 ┆ 72 │ │ 2023-01-02 ┆ 2023-01-05 ┆ 3 ┆ 72 │ │ 2023-01-03 ┆ 2023-01-06 ┆ 3 ┆ 72 │ └────────────┴────────────┴───────────────┴────────────────┘
关键说明
- 无需单独创建
_date列和time_diff中间列,通过链式调用可直接完成全流程计算 - Polars的Duration类型支持多种内置转换方法,覆盖常用精度:
dt.total_days():转换为总天数dt.total_hours():转换为总小时数dt.total_minutes():转换为总分钟数dt.total_seconds():转换为总秒数dt.total_milliseconds():转换为总毫秒数
- 这些方法自动处理单位转换,避免手动计算
24*60*60*1000这类易出错的数值
极简写法(单一精度需求)
如果只需要一种精度的结果,还能进一步简化:
df = df.with_columns( (pl.col("to").str.to_date() - pl.col("from").str.to_date()).dt.total_days().cast(pl.Int8).alias("time_diff_int") )
内容的提问来源于stack exchange,提问作者Guz
相关产品推荐
相关产品推荐

