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

PySpark3.x如何忽略timestamp日期仅按时间判断时段生成标识

PySpark timestamp字段按时间区间打标记解决方案

核心逻辑

忽略timestamp的日期部分,仅提取时分和目标区间[03:45, 10:00)做比较,匹配返回flg_1,否则返回flg_2,两种实现方式均兼容PySpark 3.x版本。

实现方式1:转HHmm格式整数判断(代码更简洁)

  1. 导入依赖函数
from pyspark.sql import functions as F
  1. 核心字段生成代码
# df为你的原始DataFrame
df_result = df.withColumn("flg",
    F.when(
        (F.date_format("time_val", "HHmm").cast("int") >= 345) &
        (F.date_format("time_val", "HHmm").cast("int") < 1000),
        F.lit("flg_1")
    ).otherwise(F.lit("flg_2"))
)

实现方式2:单独提取时分判断(逻辑更直观)

df_result = df.withColumn("flg",
    F.when(
        # 3点且分钟≥45,或者4点到9点整区间
        ((F.hour("time_val") == 3) & (F.minute("time_val") >= 45)) |
        ((F.hour("time_val") > 3) & (F.hour("time_val") < 10)),
        F.lit("flg_1")
    ).otherwise(F.lit("flg_2"))
)

测试验证

你可以用示例数据运行验证:

# 构造测试数据
test_data = [
    ("2021-08-02 03:50:00",),
    ("2021-08-01 10:05:00",)
]
test_df = spark.createDataFrame(test_data, ["time_val"])\
    .withColumn("time_val", F.col("time_val").cast("timestamp"))

# 应用逻辑后输出
test_df.withColumn("flg",
    F.when(
        (F.date_format("time_val", "HHmm").cast("int") >= 345) &
        (F.date_format("time_val", "HHmm").cast("int") < 1000),
        F.lit("flg_1")
    ).otherwise(F.lit("flg_2"))
).show(truncate=False)

输出结果和预期完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 09:27:03