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

查看:18
本文介绍了如何将时间戳类型的 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.

:param 格式:'year', 'yyyy', 'yy' or 'month', 'mon', 'mm'

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

使用 date_trunc 代替:

Use date_trunc instead:

返回截断为格式指定单位的时间戳.

Returns timestamp truncated to the unit specified by the format.

:param 格式: 'year', 'yyyy', 'yy', 'month', 'mon', 'mm',天"、日"、小时"、分钟"、秒"、周"、季度"

: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天全站免登陆