如何将时间戳类型的PySpark数据帧截断为一天? [英] How do I truncate a PySpark dataframe of timestamp type to the day?

查看:96
本文介绍了如何将时间戳类型的PySpark数据帧截断为一天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PySpark数据帧,该数据帧在一列中包含时间戳(称为"dt"列),如下所示:

I have a PySpark dataframe that includes timestamps in a column (call the column 'dt'), like this:

2018-04-07 16:46:00
2018-03-06 22:18:00

执行时:

SELECT trunc(dt, 'day') as day

...我期望:

2018-04-07 00:00:00
2018-03-06 00:00:00

但是我得到了

null
null

如何截断到一天而不是小时?

How do I truncate to the day instead of the hour?

推荐答案

您使用了错误的功能. trunc仅支持少数几种格式:

You use wrong function. trunc supports only a few formats:

将日期截断为格式指定的单位.

Returns date truncated to the unit specified by the format.

:参数格式:年","yyyy","yy"或月",星期一",毫米"

:param format: 'year', 'yyyy', 'yy' or 'month', 'mon', 'mm'

使用 date_trunc代替:

将时间戳记截断为格式指定的单位.

Returns timestamp truncated to the unit specified by the format.

:参数格式:年","yyyy","yy",月",星期一",毫米", 天",日",小时",分钟",秒",周",季度"

:param format: 'year', 'yyyy', 'yy', 'month', 'mon', 'mm', 'day', 'dd', 'hour', 'minute', 'second', 'week', 'quarter'

示例:

from pyspark.sql.functions import col, date_trunc

df = spark.createDataFrame(["2018-04-07 23:33:21"], "string").toDF("dt").select(col("dt").cast("timestamp"))

df.select(date_trunc("day", "dt")).show()
# +-------------------+                                                           
# |date_trunc(day, dt)|
# +-------------------+
# |2018-04-07 00:00:00|
# +-------------------+

这篇关于如何将时间戳类型的PySpark数据帧截断为一天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆