仅时间:使用 Spark

问题描述 投票:0回答:1

来自

Dataset
,我正在执行此请求:

select type, count(*) as nombre, max(date) as derniere_course, 
   round(avg(distance), 1) as distance, 
   avg(allure_moyenne) as allure_moyenne,
   cast(avg(allure_moyenne) as timestamp) as allure,
   round(avg(foulees_moy), 2) as foulees 
   from activites
   group by type
   order by type

其中字段具有此类型 (

printSchema()
):

 |-- date: timestamp (nullable = true)
 |-- allure_moyenne: double (nullable = true)
 |-- distance: double (nullable = true)
 |-- foulees_moy: double (nullable = true)
 |-- type: string (nullable = false)

这个请求告诉我:

"type","nombre","derniere_course","distance","allure_moyenne","allure","foulees"
"Court",160,2023-09-06 05:29:05.0,3.6,452.09375,1970-01-01 01:07:32.09375,0.86
"Long",11,2023-08-09 10:00:50.0,17.0,469.45454545454544,1970-01-01 01:07:49.454545,0.83
"Moyen",46,2023-09-02 09:34:39.0,8.1,462.5869565217391,1970-01-01 01:07:42.586956,0.84

其中

allure_moyenne
(452.1, 469.4...) 是我的跑步速度,以每公里秒数为单位,适用于短跑、中跑或长跑。

但是这里有两个问题,从

allure_moyenne
allure
的转换:

452.09375 => 1970-01-01 01:07:32.09375
469.45454545454544 => 1970-01-01 01:07:49
462.5869565217391 => 1970-01-01 01:07:42
  • 时间戳的时间部分对于我的时区来说看起来是正确的:

    • 452秒是
      7:32
      ,但时间戳显示:
      01:07:32
    • 469秒是
      7:49
      ,变成
      01:07:49
    • 462 是
      7:42
      =>
      01:07:42
  • 我只愿意看到时间戳的时间部分(或者你可以将其称为持续时间,如果更准确的话)。

但我没有发现 Spark 与时间有关。

cast(avg(allure_moyenne) as time)
不起作用,
如果
to_date(...)
to_timestamp(...)
存在,则没有
to_time(...)
功能。

我尝试过

to_timestamp(cast(avg(allure_moyenne) as timestamp), 'hh:mm:ss')
,虽然很笨拙,但也没成功。

即使只能通过将结果提取为

string
而不是
time
来实现,我也会对最终创建一个看起来像
07:32
07:32.09375
的字段的解决方案感兴趣。

apache-spark time apache-spark-sql timestamp
1个回答
0
投票

Spark 3.+ 中,它可以像

一样简单
scala> spark.sql("select substring(timestamp_seconds(452.09375d),15) as t0").show(false)
+-----------+
|t0         |
+-----------+
|07:32.09375|
+-----------+

scala> spark.version
res1: String = 3.3.2
© www.soinside.com 2019 - 2024. All rights reserved.