首页 > 解决方案 > 在 PySpark 中将整数列转换为日期

问题描述

我有一个birth_date以这种格式调用的整数列:20141130

我想将其转换为2014-11-30PySpark。

这会错误地转换日期:

.withColumn("birth_date", F.to_date(F.from_unixtime(F.col("birth_date"))))

这给出了一个错误:argument 1 requires (string or date or timestamp) type, however, 'birth_date' is of int type

.withColumn('birth_date', F.to_date(F.unix_timestamp(F.col('birth_date'), 'yyyyMMdd').cast('timestamp')))

将其转换为我想要的日期的最佳方法是什么?

标签: pysparkapache-spark-sqlpyspark-dataframes

解决方案


在将birth_date列从传递Integer给函数String之前将其转换为:to_date

from pyspark.sql import functions as F

df.withColumn("birth_date", F.to_date(F.col("birth_date").cast("string"), \
    'yyyyMMdd')).show()

+----------+
|birth_date|
+----------+
|2014-11-30|
+----------+

推荐阅读