Apache spark 如何将dataframe中的多个'string'列转换为datetime列?

Apache spark 如何将dataframe中的多个'string'列转换为datetime列?,apache-spark,pyspark,apache-spark-sql,Apache Spark,Pyspark,Apache Spark Sql,我正在将多个字符串列转换为日期时间列,但遇到以下问题: 示例列1: 2018年11月1日上午9:00:00 代码: df = df.withColumn(df.column_name, to_timestamp(df.column_name, "MM/dd/yyyy hh:mm:ss aa")) 这样行吗 第2列示例: 2019-01-10T00:00:00-05:00 代码: 这样行吗 第3列示例: 20190112 代码: 这是行不通的。我得到这个错误: AnalysisExceptio

我正在将多个字符串列转换为日期时间列,但遇到以下问题:

示例列1:

2018年11月1日上午9:00:00

代码:

df = df.withColumn(df.column_name, to_timestamp(df.column_name,  "MM/dd/yyyy hh:mm:ss aa"))
这样行吗

第2列示例:

2019-01-10T00:00:00-05:00

代码:

这样行吗

第3列示例:

20190112

代码:

这是行不通的。我得到这个错误:

AnalysisException: "cannot resolve 'unix_timestamp(t.`date`,

'yyyyMMdd')' due to data type mismatch: argument 1 requires (string or

date or timestamp) type, however, 't.`date`' is of int type.

我觉得它应该很简单,但我遗漏了一些东西。

错误是不言自明的,你需要你的列是一个字符串。 您确定您的列已经是字符串了吗?似乎不是。可以先使用column.cast将其转换为字符串

import org.apache.spark.sql.types._
df = df.withColumn(df.column_name, to_date(df.column_name.cast(StringType), "yyyyMMdd")
AnalysisException: "cannot resolve 'unix_timestamp(t.`date`,

'yyyyMMdd')' due to data type mismatch: argument 1 requires (string or

date or timestamp) type, however, 't.`date`' is of int type.
import org.apache.spark.sql.types._
df = df.withColumn(df.column_name, to_date(df.column_name.cast(StringType), "yyyyMMdd")