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

Spark字符串转日期类型失败,始终返回null值求助

解决方案

问题根源在于你使用的日期格式符与目标字符串不匹配:

  • HH 是24小时制格式符,但你的时间是12小时制(带PM标识),需替换为12小时制的 h
  • MM、dd 要求月份、日期必须是两位数字(如07),但你的示例是单数字月份(7),需改用支持1-2位数字的 M、d

修正后的代码

import pyspark.sql.functions as F
from pyspark.sql.functions import col

# 先转timestamp再转date
df = df.withColumn("test", F.to_date(F.to_timestamp(col("SinkCreatedOn"), "M/d/yyyy h:mm:ss a")))

或者可以直接用to_date指定正确格式,省略中间转timestamp的步骤:

df = df.withColumn("test", F.to_date(col("SinkCreatedOn"), "M/d/yyyy h:mm:ss a"))

验证示例

用你的测试数据验证效果:

# 构造测试数据
data = [("7/30/2022 5:21:55 PM",)]
df = spark.createDataFrame(data, ["SinkCreatedOn"])

# 执行转换
df = df.withColumn("test", F.to_date(F.to_timestamp(col("SinkCreatedOn"), "M/d/yyyy h:mm:ss a")))
df.show()

输出结果:

+--------------------+----------+
|       SinkCreatedOn|      test|
+--------------------+----------+
|7/30/2022 5:21:55 PM|2022-07-30|
+--------------------+----------+

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 09:41:29