I have a data frame with the following schema:
root
|-- date : string (nullable = true)
The value looks like 201605250000
. How can I extract date, hour and mm from this string?
Parse string:
val unix = unix_timestamp($"date", "yyyyMMddHHmm").alias("unix")
Convert to timestmap:
val ts = unix.cast("timestamp").alias("ts")
Cast to date
to get a date:
val dt = ts.cast("date").alias("dt")
Use hour
/ minute
to get time:
val h = hour(ts).alias("h")
val m = minute(ts).alias("m")
Example:
import org.apache.spark.sql.functions._
val df = Seq((1L, "201605250000")).toDF("id", "date")
df.select($"*", unix, ts, dt, h, m).show
// +---+------------+----------+--------------------+----------+---+---+
// | id| date| unix| ts| dt| h| m|
// +---+------------+----------+--------------------+----------+---+---+
// | 1|201605250000|1464127200|2016-05-25 00:00:...|2016-05-25| 0| 0|
// +---+------------+----------+--------------------+----------+---+---+
Note: For 1.5 use unix.cast("double").cast("timestamp")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With