如何将天数(作为列的值)添加到日期? [英] How to add days (as values of a column) to date?

查看:35
本文介绍了如何将天数(作为列的值)添加到日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将天数(数字)添加到 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")

有谁知道是否可以使用 column is 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆