我正在使用Spark数据集,但在从时间戳列中减去天数时遇到了问题。
我想从时间戳列中减去天,并获得具有完整日期时间格式的新列。示例:
2017-09-22 13:17:39.900 - 10 ----> 2017-09-12 13:17:39.900
有了date_sub函数,我得到了没有13:17:39.900的2017年9月12日。
发布于 2017-09-22 13:44:23
您可以将数据cast
到timestamp
和expr
以减去INTERVAL
import org.apache.spark.sql.functions.expr
val df = Seq("2017-09-22 13:17:39.900").toDF("timestamp")
df.withColumn(
"10_days_before",
$"timestamp".cast("timestamp") - expr("INTERVAL 10 DAYS")).show(false)
+-----------------------+---------------------+
|timestamp |10_days_before |
+-----------------------+---------------------+
|2017-09-22 13:17:39.900|2017-09-12 13:17:39.9|
+-----------------------+---------------------+
如果数据已经是TimestampType
,你可以跳过cast
。
发布于 2019-12-10 09:25:02
或者,您可以简单地使用pyspark +1.5中的date_sub函数:
from pyspark.sql.functions import *
df.withColumn("10_days_before", date_sub(col('timestamp'),10).cast('timestamp'))
https://stackoverflow.com/questions/46365822
复制