【问题标题】:Date and Time in Spark Timestamp format - how to calculate difference?Spark Timestamp 格式的日期和时间 - 如何计算差异?
【发布时间】:2021-08-27 03:52:02
【问题描述】:

假设我无权访问生成表的底层代码。而且我对此还比较陌生。

时间戳列的格式为“2021-08-26T11:14:08.251Z”,看起来是火花时间戳格式 - 但我不确定它是该数据类型还是字符串。

我需要计算上述格式的两个时间戳列之间的差异 - 如何将您在此处看到的内容转换为可以在 SQL 查询中运行差异计算的内容?并且不在任何底层 pyspark 代码中?

如果你能给我两个答案,一个是本机时间戳数据类型,另一个是字符串,我会很高兴!

【问题讨论】:

  • 两个时间戳列之间在什么时间范围内的差异?比如天、分、秒、小时
  • 没关系,因为我可以转换它 - 但让我们说秒。

标签: sql apache-spark


【解决方案1】:

Spark timestamp type 仅接受 yyyy-MM-dd HH:mm:ss.SSS

获取两个时间戳之间的差异,如下例所示。

示例:

df.show()
//+------------------------+-----------------------+
//|ts                      |ts1                    |
//+------------------------+-----------------------+
//|2021-08-26T11:14:08.251Z|2021-08-25 11:14:08.251|
//+------------------------+-----------------------+
df.select(unix_timestamp(to_timestamp(col("ts"))).as("ts"),unix_timestamp(to_timestamp(col("ts1"))).as("ts1")).
withColumn("diff",col("ts1")-col("ts")).show(false)
//+----------+----------+------+
//|ts        |ts1       |diff  |
//+----------+----------+------+
//|1629976448|1629915248|-61200|
//+----------+----------+------+

Update:

df.createOrReplaceTempView("tmp"

spark.sql("select ts,ts1,ts-ts1 as diff from (select unix_timestamp(to_timestamp(ts)) as ts,unix_timestamp(to_timestamp(ts1)) as ts1 from tmp)e").show(10,false)
//+----------+----------+-----+
//|ts        |ts1       |diff |
//+----------+----------+-----+
//|1629976448|1629915248|61200|
//+----------+----------+-----+

【讨论】:

  • 可以在 SQL Select 语句中使用吗?我似乎无法让它工作。
  • @DataDrivesEverything 我们绝对可以做到,请查看我的更新答案!
  • 好吧 - 是的所以基本上只是... SELECT ts , ts1 , (unix_timestamp(to_timestamp(ts))- (unix_timestamp(to_timestamp(ts1)) as diff FROM table WHERE X AND Y 这就是我需要感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多