如何添加日期(作为列的值)到日期? [英] How to add days (as values of a column) to date?
本文介绍了如何添加日期(作为列的值)到日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Spark中将天(数字)添加到日期格式列时遇到问题.我知道有一个函数date_add
带有两个参数-日期列和整数:
I have a problem with adding days (numbers) to date format columns in Spark. I know that there is a function date_add
that takes two arguments - date column and integer:
date_add(date startdate, tinyint/smallint/int days)
我想改用整数类型的列值(而不是整数本身).
I'd like to use a column value that is of type integer instead (not an integer itself).
说我有以下数据框:
val data = Seq(
(0, "2016-01-1"),
(1, "2016-02-2"),
(2, "2016-03-22"),
(3, "2016-04-25"),
(4, "2016-05-21"),
(5, "2016-06-1"),
(6, "2016-03-21"))
).toDF("id", "date")
我可以简单地在日期中添加整数:
I can simply add integers to dates:
val date_add_fun =
data.select(
$"id",
$"date",
date_add($"date", 1)
)
但是我不能使用包含值的列表达式:
But I cannot use a column expression that contains the values:
val date_add_fun =
data.select(
$"id",
$"date",
date_add($"date", $"id")
)
出现错误:
<console>:60: error: type mismatch;
found : org.apache.spark.sql.ColumnName
required: Int
date_add($"date", $"id")
有人知道date_add函数是否可以使用列?或解决方法是什么?
Does anyone know if it is possible to use column is date_add function? Or what is the workaround?
推荐答案
您可以使用expr
:
import org.apache.spark.sql.functions.expr
data.withColumn("future", expr("date_add(date, id)")).show
// +---+----------+----------+
// | id| date| future|
// +---+----------+----------+
// | 0| 2016-01-1|2016-01-01|
// | 1| 2016-02-2|2016-02-03|
// | 2|2016-03-22|2016-03-24|
// | 3|2016-04-25|2016-04-28|
// | 4|2016-05-21|2016-05-25|
// | 5| 2016-06-1|2016-06-06|
// | 6|2016-03-21|2016-03-27|
// +---+----------+----------+
selectExpr
可以类似的方式使用:
selectExpr
could be use in a similar way:
data.selectExpr("*", "date_add(date, id) as future").show
这篇关于如何添加日期(作为列的值)到日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文