如何从spark(scala)中的不同年,月和日列中获取日期

时间:2017-11-07 06:26:21

标签: scala date apache-spark dataframe

我有一个DataFrame,包括以下数据:

+----+-----+---+-----+
|Year|Month|Day|...  |
+----+-----+---+-----+
|2012|    2| 20|     |
|2011|    7|  6|     |
|2015|    3| 15|     |

我想添加一个日期

的列

4 个答案:

答案 0 :(得分:3)

将列合并在一起,然后使用unix_timestampto_date获取时间戳列。对于输入数据框df

df.withColumn("merge", concat_ws("-", $"Year", $"Month", $"Day"))
  .withColumn("date", to_date(unix_timestamp($"merge", "yyyy-MM-dd").cast("timestamp")))
  .drop("merge")

答案 1 :(得分:1)

不像Shaido那样复杂,只是

df.withColumn("date", F.to_date(F.concat_ws("-", "Year", "Month", "Day")) ).show()

在spark 2.4上工作。

答案 2 :(得分:1)

对于 Spark 3+,您可以使用 make_date 函数:

df.withColumn("date", expr("make_date(Year, Month, Day)"))

答案 3 :(得分:1)

您可以仅使用 concat_ws 函数创建字符串数据类型的日期并将其转换为日期。

import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._
//Source Data
val df = Seq((2012,2,20),(2011,7,6),(2015,3,15)).toDF("Year","Month","Day")
//using concat_ws function to create Date column and cast that column data type to date
val df1 = df.withColumn("Date",concat_ws("-",$"Year",$"Month",$"Day"))
.withColumn("Date",$"Date".cast("Date"))
display(df1)

您可以看到如下输出:

enter image description here