代码之家  ›  专栏  ›  技术社区  ›  Marc Le Bihan

仅时间:使用Spark将时间部分转换为时间戳(或从中提取),或将long转换为时间(但不转换为日期时间或时间戳)

  •  0
  • Marc Le Bihan  · 技术社区  · 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.1469.4…)是我的跑步速度,以秒/公里为单位,适用于短距离、中等距离或长跑。

    但这里有两个问题,从 allure_moynne 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
    • 我只愿意看到时间戳的时间部分(如果更准确的话,你可以称之为持续时间)。

    但我什么都没发现 火花 仅与时间有关。

    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 最后。

    0 回复  |  直到 1 年前
        1
  •  1
  •   mazaneicha    1 年前

    在里面 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