是否有任何 pyspark 函数可以添加下个月,例如 DATE_ADD(date, month(int type))

is there any pyspark function for add next month like DATE_ADD(date, month(int type))

我是 spark 的新手,是否有任何内置函数可以显示当前日期的下个月日期,比如今天是 27-12-2016,那么该函数将 return 27-01-2017。我使用了 date_add() 但没有添加月份的功能。我试过 date_add(date, 31) 但是如果这个月有 30 天怎么办。

spark.sql("select date_add(current_date(),31)") .show()

谁能帮我解决这个问题。我需要为此编写自定义函数吗?因为我仍然没有找到任何内置代码 提前致谢 卡莲

这不是 pyspark 具体的。您可以使用 add_months。自 Spark 1.5 起可用。例如:

spark.sql("select current_date(), add_months(current_date(),1)").show()
# +--------------+-----------------------------+
# |current_date()|add_months(current_date(), 1)|
# +--------------+-----------------------------+
# |    2016-12-27|                   2017-01-27|
# +--------------+-----------------------------+

您也可以使用负整数来删除月份:

spark.sql("select current_date(), add_months(current_date(),-1) as last_month").show()
# +--------------+----------+
# |current_date()|last_month|
# +--------------+----------+
# |    2016-12-27|2016-11-27|
# +--------------+----------+

我在 adding/subtracting 个月内找到的最直接的 dataframe-friendly 解决方案

from pyspark.sql import functions as F
# assume df has "current_date" column as type DateType
months_to_add = 1  # int value, could be negative
df = df.withColumn("new_date", F.add_months("current_date", months_to_add))

此结果将包括之前包含在 df 中的任何其他列。