presto和hive日期函數對比
時間格式轉換
日期格式→Unix時間戳
轉10位Unix時間戳
數據:2020-07-23 15:01:13
Presto:select to_unixtime(cast('2020-07-23 15:01:13' as timestamp))
Hive:select unix_timestamp(cast('2020-07-23 15:01:13' as timestamp))
轉13位Unix時間戳
數據:2020-07-23 15:01:13.343
Presto:select to_unixtime(cast('2020-07-23 15:01:13.343' as timestamp))*1000
Hive:select unix_timestamp(cast(substr('2020-07-23 15:01:13.343', 1, 19) as timestamp)) * 1000 + cast(substr('2020-07-23 15:01:13.343', 21) as bigint)
Unix時間戳→日期格式
10位Unix時間戳
數據:1595487673
Presto:select format_datetime(from_unixtime(1595487673),'yyyy-MM-dd HH:mm:ss')
Hive:select from_unixtime(1595487673,'yyyy-MM-dd HH:mm:ss')
13位Unix時間戳(如果不要毫秒就把concat和ss後面的.去掉)
數據:1595487673343
Presto:select concat(format_datetime(from_unixtime(1595487673343/1000),'yyyy-MM-dd HH:mm:ss.'), cast(1595487673343%1000 as varchar))
Hive:select concat(from_unixtime(cast(1595487673343/1000 as int),'yyyy-MM-dd HH:mm:ss.'), cast(1595487673343%1000 as string))
時間計算
時間間隔
數據:2020-07-24 11:42:58 – 2020-07-23 15:01:13
Presto:select date_diff('day', cast('2020-07-23 15:01:13' as timestamp), cast('2020-07-24 11:42:58' as timestamp))
Hive:select datediff('2020-07-24 11:42:58','2020-07-23 15:01:13');
這個數據,因為相差的時間小於24小時,Presto輸出的是0,而Hive是1,這個坑要注意一下。還有要注意的就是Presto是時間大的放後面,而Hive是時間大的放前面。
時間相加
數據:2020-07-24 11:42:58 + 1
Presto:select date_add('day', 1, cast('2020-07-24 11:42:58' as timestamp))
Hive:select date_add('2020-07-24 11:42:58', 1)
如果要計算相差的其他時間單位,Presto是修改前面的時間單元即可,可選有如下幾個:
Unit | Description |
---|---|
millisecond | Milliseconds |
second | Seconds |
minute | Minutes |
hour | Hours |
day | Days |
week | Weeks |
month | Months |
quarter | Quarters of a year |
year | Years |
而Hive是通過對應的時間單元函數獲取到時間單元後在進行計算,例如上面的例子2020-07-24 11:42:58 - 2020-07-23 15:01:13
,我要計算他們的小時差,那麼我可以這麼寫:
select hour('2020-07-24 11:42:58') - hour('2020-07-23 15:01:13') + datediff('2020-07-24 11:42:58','2020-07-23 15:01:13')*24