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

7lrncoxx  于 2021-07-14  发布在  Spark
关注(0)|答案(1)|浏览(271)

我试图得到一个从当前日期到前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                  |
+------------+----------+-------------------+-------------------------------+
7uzetpgm

7uzetpgm1#

只是使用 year 而不是 monthF.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")
)

相关问题