我有一個像這樣的時間戳$"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
?
uj5u.com熱心網友回復:
使用函式將時間戳轉換為秒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")
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/421902.html
標籤:
