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

PySpark:将整数格式时间取整至最近的15分钟区间

实现PySpark整数时间取整到最近15分钟间隔

这是个很常见的时间规整需求,咱们可以用PySpark的内置函数一步步实现,全程不用写UDF,性能也更优,具体操作如下:

步骤拆解与代码实现

首先得明确你的时间格式:整数925对应9点25分,2205对应22点05分,要取整到最近的15分钟节点(比如25分→30分,5分→0分)。

1. 补全时间为标准HHMM格式字符串

先把整数时间转成字符串,用lpad补前导零到4位,确保所有时间都是HHMM格式(比如925变成0925):

from pyspark.sql import functions as F

df = data.withColumn("time_str", F.lpad(F.col("TIME").cast("string"), 4, "0"))

2. 拆分小时与分钟数值

从补全的字符串里提取小时和分钟,转成整数方便计算:

df = df.withColumn("hour", F.substring("time_str", 1, 2).cast("int"))
       .withColumn("minute", F.substring("time_str", 3, 2).cast("int"))

3. 计算取整后的分钟

根据15分钟间隔规则判断:如果当前分钟除以15的余数≥7.5(15分钟的一半),就向上取整;否则向下取整。同时处理取整后分钟为60的边界情况(比如23:50会取整到次日00:00):

df = df.withColumn("rounded_minute", 
                   F.when(F.col("minute") % 15 >= 7.5, 
                          ((F.col("minute") // 15) + 1) * 15)
                    .otherwise((F.col("minute") // 15) * 15)) \
       .withColumn("adjusted_hour", 
                   F.when(F.col("rounded_minute") == 60, 
                          (F.col("hour") + 1) % 24)
                    .otherwise(F.col("hour"))) \
       .withColumn("adjusted_minute", 
                   F.when(F.col("rounded_minute") == 60, 0)
                    .otherwise(F.col("rounded_minute")))

4. 组合成目标整数时间

把调整后的小时和分钟重新组合成整数列,同时清理中间临时列:

result = df.withColumn("TIME_15_MIN_STEP", 
                       F.concat(F.col("adjusted_hour").cast("string"), 
                                F.lpad(F.col("adjusted_minute").cast("string"), 2, "0")).cast("int")) \
           .drop("time_str", "hour", "minute", "rounded_minute", "adjusted_hour", "adjusted_minute")

完整验证

运行上述代码后,执行result.show()会得到你预期的结果:

+----+------------------+
|TIME|TIME_15_MIN_STEP  |
+----+------------------+
| 925|               930|
|2205|              2200|
|2205|              2200|
|2205|              2200|
+----+------------------+

这个方案全程用PySpark原生函数,避免了自定义UDF的性能损耗,还兼顾了跨天的边界场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:52:04