如何在 Spark 3.0 中将时间戳四舍五入到 10 分钟?
How to round timestamp to 10 minutes in Spark 3.0?
我有一个像 $"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,然后使用间隔将它们添加到截断的时间戳中:
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")
)
我有一个像 $"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,然后使用间隔将它们添加到截断的时间戳中:
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")
)