Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
912 views
in Technique[技术] by (71.8m points)

dataframe - Apache Spark subtract days from timestamp column

I am using Spark Dataset and having trouble subtracting days from a timestamp column.

I would like to subtract days from Timestamp Column and get new Column with full datetime format. Example:

2017-09-22 13:17:39.900 - 10 ----> 2017-09-12 13:17:39.900

With date_sub functions I am getting 2017-09-12 without 13:17:39.900.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cast data to timestamp and expr to subtract an 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|
+-----------------------+---------------------+

If data is already of TimestampType you can skip cast.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...