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

PySpark如何基于Date和Hour列生成对应时间戳列

PySpark合并日期、小时列生成时间戳的解决方案

问题原因

原有代码返回全null是因为低版本Spark中unix_timestamp函数对自定义时间格式的解析兼容性较差,搭配cast转换类型时容易出现解析失败的问题,Spark 2.2及以上版本更推荐直接使用to_timestamp函数完成时间字符串到timestamp类型的转换。

正确实现代码

首先导入依赖的PySpark函数:

from pyspark.sql.functions import concat_ws, to_timestamp, date_format

1. 直接生成timestamp类型列

df1.withColumn("TimeStamp", to_timestamp(concat_ws(" ", df1.Date, df1.Hour), "yyyy-MM-dd HHmm")).show(truncate=False)

2. 生成与示例完全一致的带时区字符串格式

如果需要输出和Desired_Calculated_Result格式完全相同的带毫秒、时区后缀的字符串结果,可以新增一层格式化处理:

df1.withColumn("TimeStamp", to_timestamp(concat_ws(" ", df1.Date, df1.Hour), "yyyy-MM-dd HHmm"))\
   .withColumn("Desired_Calculated_Result", date_format("TimeStamp", "yyyy-MM-dd HH:mm:ss.SSSZ"))\
   .show(truncate=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:09:03