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

如何在Polars中对Duration类型数据进行取整操作?

在Polars中对Duration列进行取整的方法

Polars的dt.round操作目前仅支持date/datetime类型,无法直接对Duration列执行取整,但可以通过以下两种间接方式实现类似Pandas中Timedelta取整的效果:

方法一:通过数值转换实现取整

将Duration转换为总秒数(或其他时间单位的数值),取整后再转回Duration类型:

import polars as pl
from datetime import timedelta

df = pl.DataFrame({"times": [timedelta(seconds=15), timedelta(seconds=30), timedelta(seconds=45)]})
df = df.with_columns(
    rounded_times=pl.col("times").dt.total_seconds().round(60).cast(pl.Duration)
)
print(df)
  • dt.total_seconds():将Duration列转换为总秒数的数值列
  • round(60):按60秒(即1分钟)为单位取整
  • cast(pl.Duration):将取整后的数值转回Duration类型

方法二:借助Datetime中转实现取整

把Duration叠加到一个固定的基准Datetime上,对生成的Datetime列取整后,再减去基准Datetime得到取整后的Duration:

import polars as pl
from datetime import timedelta, datetime

base_datetime = datetime(2000, 1, 1)  # 任意固定的基准时间
df = pl.DataFrame({"times": [timedelta(seconds=15), timedelta(seconds=30), timedelta(seconds=45)]})
df = df.with_columns(
    rounded_times=(pl.lit(base_datetime) + pl.col("times")).dt.round("1m") - pl.lit(base_datetime)
)
print(df)
  • 利用基准Datetime + Duration得到Datetime列,此时可以使用dt.round("1m")按1分钟取整
  • 最后减去基准Datetime,还原为取整后的Duration类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:10:59