我正在尝试分析当前为字符串类型的日期列。格式为
2005-04-24T09:12:49Z
我有Spark 2.1版。我已经尝试了以下
spark.sql("SELECT TO_DATE(Date) FROM df").show()
这返回 2005-04-24 但没有时间戳。
接下来我尝试了
val ts = unix_timestamp($"Date", "yyyy-dd-MM HH:mm:ss").cast("timestamp")
df.withColumn("Date", ts).show()
这将返回所有空值
然后我尝试了
spark.sql("select TO_DATE(Date_Resulted, 'yyyy-MM-ddTHH:mm:ssZ') AS date from lab").show()
但这只是返回错误:
org.apache.spark.sql.AnalysisException: Invalid number of arguments for function to_date; line 1 pos 7
必须有一种简单的方法来解析此字符串日期列以返回类型DateTime。任何帮助将不胜感激
答案 0 :(得分:3)
有多种方法可以在Spark中获取日期时间。
让我们使用以下示例数据:
val df=Seq("2005-04-24T09:12:49Z").toDF("time_stamp")
df.createOrReplaceTempView("tmp")
//in spark sql api
spark.sql("select to_date(time_stamp)dt from tmp").show()
//in dataframe api
df.withColumn("dt",to_date('time_stamp)).select("dt").show()
Result:
//+----------+
//| dt|
//+----------+
//|2005-04-24|
//+----------+
//in spark sql api
spark.sql("""select timestamp(from_unixtime(unix_timestamp(time_stamp,"yyyy-MM-dd'T'hh:mm:ss'Z'"),"yyyy-MM-dd hh:mm:ss")) as ts from tmp""").show()
//in dataframe api
df.withColumn("dt",from_unixtime(unix_timestamp('time_stamp,"yyyy-MM-dd'T'hh:mm:ss'Z'"),"yyyy-MM-dd hh:mm:ss").cast("timestamp")).select("dt").show()
// Result:
// +-------------------+
// | ts|
// +-------------------+
// |2005-04-24 09:12:49|
// +-------------------+
//in spark sql api
spark.sql("""select timestamp(unix_timestamp(time_stamp,"yyyy-MM-dd'T'hh:mm:ss'Z'")) as ts from tmp""").show()
//in dataframe api
df.withColumn("dt",unix_timestamp('time_stamp,"yyyy-MM-dd'T'hh:mm:ss'Z'").cast("timestamp")).select("dt").show()
// Result:
// +-------------------+
// | ts|
// +-------------------+
// |2005-04-24 09:12:49|
// +-------------------+
//in spark sql api
spark.sql("select to_timestamp(time_stamp)ts from tmp").show()
//in dataframe api
df.withColumn("dt",to_timestamp('time_stamp)).select("dt").show()
// Result:
// +-------------------+
// | ts|
// +-------------------+
// |2005-04-24 04:12:49|
// +-------------------+
//in spark sql api
spark.sql("""select to_timestamp(time_stamp,"yyyy-MM-dd'T'hh:mm:ss'Z'")ts from tmp""").show()
//in dataframe api
df.withColumn("dt",to_timestamp($"time_stamp","yyyy-MM-dd'T'hh:mm:ss'Z'")).select("dt").show()
// Result:
// +-------------------+
// | ts|
// +-------------------+
// |2005-04-24 09:12:49|
// +-------------------+
答案 1 :(得分:3)
这将起作用:
val df = Seq("2005-04-24T09:12:49Z").toDF("date")
df
.withColumn("date_converted", to_timestamp($"date", "yyyy-MM-dd'T'HH:mm:ss'Z'"))
.show()
给予:
+--------------------+-------------------+
| date| date_converted|
+--------------------+-------------------+
|2005-04-24T09:12:49Z|2005-04-24 09:12:49|
+--------------------+-------------------+