1. 程式人生 > 實用技巧 >presto和hive日期函式對比

presto和hive日期函式對比

時間格式轉換

日期格式→Unix時間戳

轉10位Unix時間戳

資料:2020-07-23 15:01:13

Prestoselect to_unixtime(cast('2020-07-23 15:01:13' as timestamp))

Hiveselect unix_timestamp(cast('2020-07-23 15:01:13' as timestamp))

轉13位Unix時間戳

資料:2020-07-23 15:01:13.343

Prestoselect to_unixtime(cast('2020-07-23 15:01:13.343' as timestamp))*1000

Hiveselect 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

Prestoselect format_datetime(from_unixtime(1595487673),'yyyy-MM-dd HH:mm:ss')

Hiveselect from_unixtime(1595487673,'yyyy-MM-dd HH:mm:ss')

13位Unix時間戳(如果不要毫秒就把concat和ss後面的.去掉)

資料:1595487673343

Prestoselect concat(format_datetime(from_unixtime(1595487673343/1000),'yyyy-MM-dd HH:mm:ss.'), cast(1595487673343%1000 as varchar))

Hiveselect 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

Prestoselect date_diff('day', cast('2020-07-23 15:01:13' as timestamp), cast('2020-07-24 11:42:58' as timestamp))

Hiveselect 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

Prestoselect date_add('day', 1, cast('2020-07-24 11:42:58' as timestamp))

Hiveselect 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