You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala:如何从Epoch时间获取数字格式的星期几

基于Epoch时间获取星期几(Spark Scala实现)

没问题!要基于Epoch时间(秒级)在Spark中获取以周一为1的数字星期几,其实只需要先把Epoch时间转换成Spark的Timestamp类型,再用date_format函数指定对应的格式模式就行,具体实现如下:

完整代码示例

import org.apache.spark.sql.functions._
import spark.sqlContext.implicits._

// 构造包含Epoch秒级时间的示例DataFrame
val df = Seq(1576683390L, 1561350079L, 1571232000L).toDF("epoch_seconds")

// 转换Epoch时间并计算星期几
df.withColumn("timestamp", to_timestamp(col("epoch_seconds").cast("long")))
  .withColumn("week_day_number", date_format(col("timestamp"), "u"))
  .withColumn("week_day_abb", date_format(col("timestamp"), "E"))
  .show(false)

输出结果示例

+-------------+-------------------+---------------+------------+
|epoch_seconds|timestamp          |week_day_number|week_day_abb|
+-------------+-------------------+---------------+------------+
|1576683390   |2019-12-18 03:36:30|3              |Wed         |
|1561350079   |2019-06-24 12:01:19|1              |Mon         |
|1571232000   |2019-10-17 00:00:00|4              |Thu         |
+-------------+-------------------+---------------+------------+

关键步骤说明

  • 转换Epoch到Timestamp:使用to_timestamp(col("epoch_seconds").cast("long")),将秒级的Epoch时间转换为Spark的Timestamp类型(如果你的Epoch是毫秒级,需要先除以1000:to_timestamp(col("epoch_milliseconds").cast("long") / 1000))。
  • 获取数字星期几:date_format的"u"模式是ISO标准的星期表示,周一为1,周日为7,完全符合你的需求。
  • 获取星期缩写:"E"模式会返回星期的英文缩写(如Mon、Sat)。

替代方案(使用dayofweek函数)

如果你更习惯用dayofweek函数,它默认返回周日为1、周六为7,你可以通过逻辑调整成周一为1:

df.withColumn("timestamp", to_timestamp(col("epoch_seconds").cast("long")))
  .withColumn("week_day_number", 
              when(dayofweek(col("timestamp")) === 1, 7)
              .otherwise(dayofweek(col("timestamp")) - 1))
  .show(false)

不过直接用date_format的"u"模式会更简洁直观。

内容的提问来源于stack exchange,提问作者Sekar Ramu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:02:58