【问题标题】:Spark SQL datediff in secondsSpark SQL datediff 以秒为单位
【发布时间】:2016-12-27 09:48:07
【问题描述】:

我有以下代码:

table.select(datediff(table.col("Start Time"), table.col("End Time"))).show()

日期格式为2016-05-19 09:23:28 (YYYY-MM-DD HH:mm:SS)

函数datediff 计算天差。但我想以秒为单位。

【问题讨论】:

  • 查看THIS帖子
  • 谢谢,但它不起作用。如果我添加例如“SECONDS”或“sec”作为 datediff 函数的选项,那么 Eclipse 会显示一条错误消息 --> 函数“datediff”的选项太多。
  • table.withColumn("date_diff", (unix_timestamp($"Start Time") - unix_timestamp($"End Time")))

标签: scala apache-spark apache-spark-sql


【解决方案1】:

您可以使用unix_timestamp() 函数将日期转换为秒。

import org.apache.spark.sql.functions._

//For $ notation columns // Spark 2.0
import spark.implicits._

table.withColumn("date_diff", 
   (unix_timestamp($"Start Time") - unix_timestamp($"End Time"))
).show()

编辑:(根据评论)

UDF 将秒数转换为 HH:mm:ss

sqlContext.udf.register("sec_to_time", (s: Long) => 
   ((s / 3600L) + ":" + (s / 60L) + ":" + (s % 60L))
)

//Use registered UDF now
table.withColumn("date_diff", 
   sec_to_time(unix_timestamp($"Start Time") - unix_timestamp($"End Time"))
).show()

【讨论】:

  • 好处是unix_timestamp 也处理了(对我来说)varchar 输入,所以我申请的cast(... as timestamp) 步骤也可以包含在这个调用中
  • @MichaelChirico:不错的收获。是的,必须颠倒过来。
  • UDF 中的 (s / 60L) 将给出总分钟数,即如果持续时间超过 1 小时,分钟部分将是错误的
  • 应该是sqlContext.udf.register("sec_to_time", (s: Long) => ((s / 3600L) + " Hr : " + ( (s % 3600L) / 60L) + " Min : " + (s % 60L) + " Sec ") )
  • @mrsrinivas 我们可以在 Spark SQL 中使用这个unix_timestamp 吗?
猜你喜欢
  • 1970-01-01
  • 2019-08-27
  • 2019-07-31
  • 2019-05-08
  • 2010-10-30
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2011-07-27
相关资源
最近更新 更多