PySpark可以将时间戳记整小时吗?

时间:2019-06-09 12:51:32

标签: time pyspark unix-timestamp

我有兴趣将时间戳取整为整小时。到目前为止,我要四舍五入到最近的一个小时。例如:

df.withColumn("Full Hour", hour((round(unix_timestamp("Timestamp")/3600)*3600).cast("timestamp")))

但是此“舍入”函数使用HALF_UP舍入。这意味着:23:56的结果为00:00,但我宁愿选择23:00。这可能吗?我没有找到用于设置函数中舍入行为的选项字段。

1 个答案:

答案 0 :(得分:0)

我认为您太过复杂了。 Hour函数默认情况下返回时间戳的小时部分。

from pyspark.sql.functions import to_timestamp
from pyspark.sql import Row

df = (sc
    .parallelize([Row(Timestamp='2016_08_21 11_59_08')])
    .toDF()
    .withColumn("parsed", to_timestamp("Timestamp", "yyyy_MM_dd hh_mm_ss")))

df2 = df.withColumn("Full Hour", hour(unix_timestamp("parsed").cast("timestamp")))

df2.show()

输出:

+-------------------+-------------------+---------+
|          Timestamp|             parsed|Full Hour|
+-------------------+-------------------+---------+
|2016_08_21 11_59_08|2016-08-21 11:59:08|       11|
+-------------------+-------------------+---------+