我有一个包含以下架构的数据框:
root
|-- date : string (nullable = true)
该值看起来像201605250000
。如何从此字符串中提取日期,小时和毫米?
答案 0 :(得分:8)
解析字符串:
val unix = unix_timestamp($"date", "yyyyMMddHHmm").alias("unix")
转换为timestmap:
val ts = unix.cast("timestamp").alias("ts")
转换为date
以获取日期:
val dt = ts.cast("date").alias("dt")
使用hour
/ minute
获取时间:
val h = hour(ts).alias("h")
val m = minute(ts).alias("m")
示例:
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|
// +---+------------+----------+--------------------+----------+---+---+
注意:1.5使用unix.cast("double").cast("timestamp")