如何将列的类型从字符串转换为日期

Maa*_*ten 1 python string datetime date pyspark

我有一个非常简单的问题,我找不到简单的答案:我想将 Pyspark DataFrame 中的列类型从字符串转换为日期,我该怎么做?

我尝试了以下方法:

df.withColumn('dates', datetime.strpdate(col('date'), %Y%m%d))
Run Code Online (Sandbox Code Playgroud)

df.withColumn('dates', datetime.strpdate(df.date, %Y%m%d))
Run Code Online (Sandbox Code Playgroud)

但在每种情况下我都会收到以下错误:TypeError: strptime() argument 1 must be str, not Column.

显然,col('date')anddf.date被解释为 Column 而不是所保存的字符串。我怎样才能解决这个问题?

nee*_*ani 5

如果格式为“yyyy-MM-dd”,您可以使用“ cast ”函数将字符串列转换为日期,或者您可以使用“ to_date ”函数,这是更通用的函数,您也可以在其中指定输入格式。

这是示例代码。

代码

# Create DaraFrame
df = spark.createDataFrame([(1, "2020-06-03", "2020/06/03"), (2, "2020-05-01", "2020/05/01")] , ["id", "date_fmt_1", "date_fmt_2"])

# Convert the string columne to date.
df1 = (df
         # approach - 1: use cast function if the format is "yyyy-MM-dd"
         .withColumn("date_1", df["date_fmt_1"].cast("date"))
       # Approach - 2 : use to_date function and specify the input format. "yyyy/MM/dd" in our case 
       .withColumn("date_2", to_date("date_fmt_2", "yyyy/MM/dd"))
       # If you don't specify any format, it will take spark default format "yyyy-MM-dd"
        .withColumn("date_3", to_date(df["date_fmt_1"])))

# Print the schema
df1.printSchema()
Run Code Online (Sandbox Code Playgroud)

模式输出

root
 |-- id: long (nullable = true)
 |-- date_fmt_1: string (nullable = true)
 |-- date_fmt_2: string (nullable = true)
 |-- date_1: date (nullable = true)
 |-- date_2: date (nullable = true)
 |-- date_3: date (nullable = true)
Run Code Online (Sandbox Code Playgroud)

显示数据。

df1.show()
Run Code Online (Sandbox Code Playgroud)

数据帧输出

+---+----------+----------+----------+----------+----------+
| id|date_fmt_1|date_fmt_2|    date_1|    date_2|    date_3|
+---+----------+----------+----------+----------+----------+
|  1|2020-06-03|2020/06/03|2020-06-03|2020-06-03|2020-06-03|
|  2|2020-05-01|2020/05/01|2020-05-01|2020-05-01|2020-05-01|
+---+----------+----------+----------+----------+----------+
Run Code Online (Sandbox Code Playgroud)

有关 Spark DateTime 函数的更多信息,您可以访问此博客:https://medium.com/expedia-group-tech/deep-dive-into-apache-spark-datetime-functions-b66de737950a

我希望这有帮助。