【问题标题】:Any better way to convert timestamp (HH:mm:ss) to Seconds in Hive在 Hive 中将时间戳 (HH:mm:ss) 转换为秒的任何更好的方法
【发布时间】:2021-01-29 08:39:38
【问题描述】:

我有一个字符串类型的配置单元字段,其时间戳格式如下: 高:毫米:秒 毫米: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
                

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

【问题讨论】:

  • 列duration的数据类型是什么?
  • String : 抱歉忘了在我的原帖中提及!
  • 那么你的方法对我来说很好。
  • 你能假设一些事情重写 sql 吗? 1. 用这个LEN(duration) -LEN(REPLACE(duration,':')) =2 或1 替换like。 2. 是否可以用substr 替换split?例如,如果您知道前 2 个字符将在那里,那么您可以使用 SUBSTR(duration,1,2) * 3600 等等。如果您想了解更多信息,我可以在 sql 方面提供帮助。

标签: sql time hive timestamp hiveql


【解决方案1】:

在 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

返回完全相同。

【讨论】:

  • 感谢您的回复。通过减去 21600(1970-01-01 的纪元)做了微小的变化。输入为(--使用你的表而不是这个选择堆栈(3,'10:30:40','01:00','40')作为持续时间)选择持续时间,当持续时间像'%:%: %' 然后 unix_timestamp(duration,'HH:mm:ss') - 21600 当持续时间像 '%:%' 然后 unix_timestamp(duration,'mm:ss') - 21600 否则持续时间作为输入结果结束
猜你喜欢
  • 1970-01-01
  • 2018-11-29
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 2011-06-17
相关资源
最近更新 更多