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

PySpark中如何通过日期列与字符串列创建时间戳列?

PySpark 合并日期与时间列生成时间戳列解决方案

原代码的问题

你的代码存在三个关键错误:

  • concat_ws使用空字符串拼接,导致日期和时间无分隔符(比如变成2020-11-0315:34:02),to_timestamp无法解析格式
  • 错误地将时间格式字符串'yyyy-MM-dd HH:mm:ss'传入concat_ws,这个参数应该作为to_timestamp的第二个参数
  • 列名不匹配:原数据的时间列是Times (String),代码里写的是Time

正确代码示例

假设你的DataFrame名为df,正确写法如下:

import pyspark.sql.functions as F

df = df.select(
    F.col("Date"),
    F.col("Times (String)"),
    F.to_timestamp(
        F.concat_ws(" ", F.col("Date"), F.col("Times (String)")),
        "yyyy-MM-dd HH:mm:ss"
    ).alias("desired_column")
)

代码说明

  • concat_ws(" ", ...):用空格作为分隔符,将日期列和时间列拼接成yyyy-MM-dd HH:mm:ss格式的字符串
  • to_timestamp(拼接后的字符串, 格式):指定格式将拼接后的字符串转换为时间戳类型

另一种等价写法

也可以直接用字符串拼接运算符,效果一致:

df = df.select(
    F.col("Date"),
    F.col("Times (String)"),
    F.to_timestamp(
        F.col("Date") + " " + F.col("Times (String)"),
        "yyyy-MM-dd HH:mm:ss"
    ).alias("desired_column")
)

内容的提问来源于stack exchange,提问作者f.ivy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:27:02