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

如何在Polars Python中将字符串转为Duration类型并转成秒数

Polars字符串转时长秒数解决方案

问题原因

Polars的str.strptime(pl.Duration, "%H:%M:%S")不支持小时数≥24的格式,因为%H对应的是0-23的小时范围,所以"24:00:00"会解析失败。


方案1:模仿Power Query替换格式解析

将"24:00:00"替换为带天数的格式"1.00:00:00",再用支持天数的格式字符串解析为Duration,最后提取总秒数并转为int32:

import polars as pl

df = pl.DataFrame(
    {
        "a": ["24:00:00", "00:45:00"]
    }
)

df = df.with_columns(
    pl.col("a")
    # 替换24:00:00为带天数的格式
    .str.replace("^24:00:00$", "1.00:00:00")
    # 用包含天数的格式解析Duration
    .str.strptime(pl.Duration, "%d.%H:%M:%S", strict=False)
    # 提取总秒数并转为int32
    .dt.total_seconds()
    .cast(pl.Int32)
    .alias("a_seconds")
)

print(df)

输出结果:

shape: (2, 2)
┌──────────┬────────────┐
│ a        ┆ a_seconds  │
│ ---      ┆ ---        │
│ str      ┆ i32        │
╞══════════╪════════════╡
│ 24:00:00 ┆ 86400      │
│ 00:45:00 ┆ 2700       │
└──────────┴────────────┘

方案2:直接拆分计算总秒数(更通用)

无需替换格式,直接拆分时分秒字符串,计算总秒数,支持任意小时数(比如25:30:00这类超出24的情况也能处理):

import polars as pl

df = pl.DataFrame(
    {
        "a": ["24:00:00", "00:45:00"]
    }
)

df = df.with_columns(
    (
        # 提取小时部分转int32并乘以3600
        pl.col("a").str.split(":").list.get(0).cast(pl.Int32) * 3600
        # 提取分钟部分转int32并乘以60
        + pl.col("a").str.split(":").list.get(1).cast(pl.Int32) * 60
        # 提取秒部分转int32
        + pl.col("a").str.split(":").list.get(2).cast(pl.Int32)
    ).alias("a_seconds")
)

print(df)

输出结果和方案1一致,且能处理更复杂的时长字符串。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:07:22