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

如何在PySpark中便捷将时长字符串列转换为秒数?

在PySpark中将时长字符串转换为秒数的简便方法

你可以利用PySpark的内置函数避免手动拆分字符串,具体分两种场景处理:

方法1:使用to_interval(PySpark 3.0+推荐)

PySpark 3.0及以上版本提供的to_interval函数,可直接将特定格式的时长字符串转为时间间隔类型,再将间隔类型转为秒数:

步骤:

  1. 调整时长字符串格式,在天数与时分秒之间插入days,让to_interval能够识别
  2. 将转换后的间隔类型通过cast("long")转为总秒数

示例代码:

from pyspark.sql import SparkSession
from pyspark.sql.functions import to_interval, regexp_replace, col

# 初始化Spark会话
spark = SparkSession.builder.appName("DurationConverter").getOrCreate()

# 测试数据
data = [
    (1, "00 00:00:34"),
    (2, "00 00:04:37"),
    (3, "120 00:04:37")
]
df = spark.createDataFrame(data, ["id", "duration"])

# 转换逻辑
df = df.withColumn(
    "duration_interval",
    to_interval(regexp_replace(col("duration"), " ", " days "))
).withColumn(
    "duration_seconds",
    col("duration_interval").cast("long")
)

# 查看结果
df.select("id", "duration_seconds").show()

输出结果:

+---+----------------+
| id|duration_seconds|
+---+----------------+
|  1|              34|
|  2|             277|
|  3|        10368277|
+---+----------------+

方法2:兼容低版本PySpark(无to_interval时)

如果使用PySpark 3.0以下版本,可以借助时间戳差值计算:
将时长字符串拼接到基准日期(如1970-01-01)后转为时间戳,再减去基准日期的时间戳,差值即为总秒数。

示例代码:

from pyspark.sql import SparkSession
from pyspark.sql.functions import unix_timestamp, lit, to_timestamp

spark = SparkSession.builder.appName("DurationConverter").getOrCreate()

data = [
    (1, "00 00:00:34"),
    (2, "00 00:04:37"),
    (3, "120 00:04:37")
]
df = spark.createDataFrame(data, ["id", "duration"])

# 转换逻辑
df = df.withColumn(
    "duration_seconds",
    unix_timestamp(to_timestamp(lit("1970-01-01 ") + col("duration"), "yyyy-MM-dd HH:mm:ss"))
    - unix_timestamp(lit("1970-01-01"))
)

df.select("id", "duration_seconds").show()

两种方法均无需手动拆分天、时、分、秒字段,完全依赖内置函数完成转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:37:33