首页 > 解决方案 > 在 Hive 中将时间戳 (HH:mm:ss) 转换为秒的任何更好的方法

问题描述

我有一个字符串类型的配置单元字段,其时间戳采用以下格式:HH:mm:ss mm:ss ss 我需要将它们转换如下:

Input: 
10:30:40
   30:40
      40
Output Expected:
    10:30:40 = (10*3600) + (30 * 60) + 40  = 37,840
       30:40 =             (30 * 60) + 40  =   1840
          40 =                         40  =     40     

我试着做这样的事情

case 
    when duration  like '%:%:%' then 
            split(duration, ':')[0] * 3600 + 
            split(duration, ':')[1] * 60 + 
            split(duration, ':')[2] 
        when duration  like  '%:%' then 
            split(duration, ':')[0] * 60 + 
            split(duration, ':')[1] 
        else 
            duration 
        end
                

这可行,但似乎效率低下。当我必须处理数十亿条记录时,有没有更好的方法来做同样的事情。

标签: sqltimehivetimestamphiveql

解决方案


在 hive 中执行时,您的表达式不会产生太多额外的负载。您可以使用函数稍微简化查询unix_timestamp,但它不会运行得更快。

with input as(--use your table instead of this
select stack(3, '10:30:40',
                '30:40',
                '40') as duration
)

select duration, case when duration like '%:%:%' then unix_timestamp(duration,'HH:mm:ss') 
                      when duration like '%:%'   then unix_timestamp(duration,'mm:ss') 
                      else duration
                  end as result
 from input

结果:

duration    result
10:30:40    37840
30:40       1840
40          40

或者更简单:

select duration, coalesce(unix_timestamp(duration,'HH:mm:ss'), unix_timestamp(duration,'mm:ss'), duration) as result

返回完全相同。


推荐阅读