如何在Spark 3.0中将时间戳四舍五入到10分钟



我有一个类似于$"my_col":中的时间戳

2022-01-21 22:11:11

date_trunc("minute",($"my_col"))

2022-01-21 22:11:00

date_trunc("hour",($"my_col"))

2022-01-21 22:00:00

什么是Spark 3.0获得的方法

2022-01-21 22:10:00

使用unix_timestamp函数将时间戳转换为秒,然后通过除以600(10分钟(进行取整,将除法结果取整,然后再次乘以600:

val df = Seq(
("2022-01-21 22:11:11"),
("2022-01-21 22:04:04"),
("2022-01-21 22:19:34"),
("2022-01-21 22:57:14")
).toDF("my_col").withColumn("my_col", to_timestamp($"my_col"))
df.withColumn(
"my_col_rounded",
from_unixtime(round(unix_timestamp($"my_col") / 600) * 600)
).show
//+-------------------+-------------------+
//|my_col             |my_col_rounded     |
//+-------------------+-------------------+
//|2022-01-21 22:11:11|2022-01-21 22:10:00|
//|2022-01-21 22:04:04|2022-01-21 22:00:00|
//|2022-01-21 22:19:34|2022-01-21 22:20:00|
//|2022-01-21 22:57:14|2022-01-21 23:00:00|
//+-------------------+-------------------+

您还可以将原始时间戳截断为小时,将您的回合的分钟数设为10,并使用interval将其添加到截断的时间戳中:

df.withColumn(
"my_col_rounded",
date_trunc("hour", $"my_col") + format_string(
"interval %s minute",
expr("round(extract(MINUTE FROM my_col)/10.0)*10")
).cast("interval")
)

最新更新