Spark 3.0及以上版本如何提取日期对应的年周数?
问题原因
你之前用的格式符W(大写)是Spark中代表月内周数的标识,所以无法返回正确的年周数。
最优实现方案
Spark 3.0+提供了原生内置函数直接提取年周数,不需要创建临时视图执行SQL,直接在现有链式调用中新增一行即可:
.withColumn("week_of_year", weekofyear(col("day_id")))
该函数返回值为1-53的整数(符合ISO周标准,少数年份存在第53周),如果你的业务要求严格限制取值范围为1-52,可以通过条件判断将第53周归到对应年份的周数,示例如下:
.withColumn("week_of_year", when(weekofyear(col("day_id")) == 53, 1).otherwise(weekofyear(col("day_id"))) )
备选实现(使用date_format)
如果习惯用date_format函数实现,把格式符替换为小写w后再转成整数类型即可:
.withColumn("week_of_year", date_format(col("day_id"), "w").cast("int"))
整合后完整代码示例
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")) .withColumn("week_of_year", weekofyear(col("day_id")))
注意事项
Spark默认遵循ISO周规则,以周一为一周首日,每年第一个包含周四的周为当年第一周。如果你的业务周规则不同(比如周日为周首),可以调整spark.sql.legacy.weekOfYear配置参数适配业务规则。
内容的提问来源于stack exchange,提问作者ATidedHumour
相关产品推荐
相关产品推荐

