如何将一年中的月份转换为第一个月

时间:2021-04-09 07:18:47

标签: dataframe apache-spark date pyspark apache-spark-sql

我正在尝试获取从当前日期到前 3 年的日期范围 之前 3 年的数据应该从 1 月 1 日开始。 以下是我尝试过的代码片段。

dateDF = spark.sql("select current_date() as current_date, add_months(current_date(),-36) as end_date")
dateDF =  dateDF.withColumn("end_date_first_date", F.trunc("end_date", "month")).withColumn("end_date_first_date_first_month",lit(''))
dateDF.show()

+------------+----------+-------------------+-------------------------------+
|current_date|  end_date|end_date_first_date|end_date_first_date_first_month|
+------------+----------+-------------------+-------------------------------+
|  2021-04-09|2018-04-09|         2018-04-01|                               |
+------------+----------+-------------------+-------------------------------+

在这里我可以得到第一次约会,但是我怎么才能得到第一个月。有没有预定义的函数?

预期输出

+------------+----------+-------------------+-------------------------------+
|current_date|  end_date|end_date_first_date|end_date_first_date_first_month|
+------------+----------+-------------------+-------------------------------+
|  2021-04-09|2018-04-09|         2018-04-01|   2018-01-01                  |
+------------+----------+-------------------+-------------------------------+

1 个答案:

答案 0 :(得分:2)

只需在 year 中使用 month 而不是 F.trunc

dateDF = dateDF.withColumn(
    "end_date_first_date", 
    F.trunc("end_date", "month")
).withColumn(
    "end_date_first_date_first_month",
    F.trunc("end_date", "year")
)
相关问题