首页 > 解决方案 > 如何在 Spark 3.0+ 中获得一年中的一周?

问题描述

我正在尝试创建一个包含日、月等列的日历文件。以下代码可以正常工作,但我找不到一种干净的方法来提取一年中的一周(1-52)。在spark 3.0+中,以下代码行不起作用:.withColumn("week_of_year", date_format(col("day_id"), "W"))

我知道我可以创建一个视图/表,然后在其上运行 SQL 查询以提取week_of_year,但是没有更好的方法吗?`

df.withColumn("day_id", to_date(col("day_id"), date_fmt))
.withColumn("week_day", date_format(col("day_id"), "EEEE"))
.withColumn("month_of_year", date_format(col("day_id"), "M"))
.withColumn("year", date_format(col("day_id"), "y"))
.withColumn("day_of_month", date_format(col("day_id"), "d"))
.withColumn("quarter_of_year", date_format(col("day_id"), "Q"))

标签: scalaapache-sparkapache-spark-sql

解决方案


您看到的异常,建议使用 EXTRACT SQL 函数而不是https://spark.apache.org/docs/3.0.0/api/sql/index.html#extract

 val df =  Seq(("2019-11-16 16:50:59.406")).toDF("input_timestamp")
 df.selectExpr("input_timestamp", "extract(week FROM input_timestamp) as w").show
 +--------------------+---+
 |     input_timestamp|  w|
 +--------------------+---+
 |2019-11-16 16:50:...| 46|
 +--------------------+---+

推荐阅读