【问题标题】:In PySpark how to round a timestamp value to the nearest minute?在 PySpark 中,如何将时间戳值四舍五入到最接近的分钟?
【发布时间】:2021-11-16 06:08:54
【问题描述】:
我正在尝试对 PySpark 中的时间戳列进行四舍五入,我无法使用 date_trunc 函数,因为它只会向下舍入值..
例如:
Real Value Expected Round Up/Down
2020-11-03 18:25:04 -> 2020-11-03 18:25:00
2020-11-03 18:21:44 -> 2020-11-03 18:22:00
我不想使用 pandas 来解决问题。
【问题讨论】:
标签:
python
pyspark
timestamp
aws-glue
apache-zeppelin
【解决方案1】:
您可以将 30 秒添加到时间戳,然后截断到分钟。这假设您的列名为“时间”
import pyspark.sql.functions as f
df = df.withColumn('time_minute', f.date_trunc('minute', f.col('time') + f.expr('INTERVAL 30 SECONDS')))
+-------------------+-------------------+
| time| time_minute|
+-------------------+-------------------+
|2020-11-03 18:25:04|2020-11-03 18:25:00|
|2020-11-03 18:21:44|2020-11-03 18:22:00|
+-------------------+-------------------+