from_unixtime:時間戳轉日期函數
用法:from_unixtime(bigint unixtime[, stringformat])
返回值: string
substr(from_unixtime(unix_timestamp()),1,10)
結果為:2017-01-03
select from_unixtime(unix_timestamp('20180905','yyyymmdd'),'yyyy-mm-dd')
from dw.ceshi_data
結果如下:
2018-09-05
2018-09-05轉成20180905
select from_unixtime(unix_timestamp('2018-09-05','yyyy-mm-dd'),'yyyymmdd')
from dw.ceshi_data
結果如下:
20180905
用法:unix_timestamp(string date)
註意:裏面格式必須是yyyy-MM-dd HH:mm:ss,如果不是會返回null值
返回值: bigint
from dw.ceshi_data;
結果如下:
1536120063
獲取當前日期的時間戳:
select unix_timestamp()
from dw.ceshi_data;
結果如下:
1536126324
hive表中,存放著無法直接識別的字符串格式的時間,如'20170728102031',要計算兩個時間相差的秒數。
1、先將字符串調整為hive可以識別的格式,即將形如'20170728102031' 轉成 '2017-07-28 10:20:31'。 因為hive的 regexp_replace 不支持子語句,沒法壹次轉換,只能用萬能的 substr 和拼接函數來寫了
select concat(substr('20170728102031',1,4),'-',
substr('20170728102031',5,2),'-',
substr('20170728102031',7,2),' ',
substr('20170728102031',9,2),':',
substr('20170728102031',11,2),':',
substr('20170728102031',13,2))
select unix_timestamp(concat(substr('20170728102031',1,4),'-',substr('20170728102031',5,2),'-',
substr('20170728102031',7,2),' ',
substr('20170728102031',9,2),':',
substr('20170728102031',11,2),':',
substr('20170728102031',13,2))) - unix_timestamp(concat(substr('20170728112031',1,4),'-',
substr('20170728112031',5,2),'-',
substr('20170728112031',7,2),' ',
substr('20170728112031',9,2),':',
substr('20170728112031',11,2),':',
substr('20170728112031',13,2)))
hive > select create_time ,datediff(from_unixtime(unix_timestamp(),’yyyy-MM-dd HH:mm:ss’), create_time) from test;
結果:當前時間是2017-11-16 與create_time的11-10之間差了6天,輸出6;
hive >select datediff(’2012-12-08′,’2012-05-09′) from dual;
213
日期時間轉日期函數: to_date語法: to_date(string timestamp) 返回:string
hive> select to_date(’2011-12-08 10:03:01′) from dual;
2011-12-08
2011
以下可以取到 month,hour,minute,second 用法和上面的壹樣
日期轉周函數: weekofyear語法: weekofyear (string date) 返回值: int 說明: 返回日期在當前的周數。
hive> select weekofyear(’2011-12-08 10:03:01′) from dual;
49
日期增加函數: date_add語法:
date_add(string startdate, int days)
返回值: string
說明: 返回開始日期startdate增加days天後的日期
舉例:
hive> select date_add(’2012-12-08′,10) from dual;
2012-12-18
日期減少函數: date_sub語法: date_sub (string startdate, int days)
返回值: string
說明: 返回開始日期startdate減少days天後的日期。
舉例:
hive> select date_sub(’2012-12-08′,10) from dual;
2012-11-28
所以我們利用其中的hour和datediff來獲取create_time與當前時間的小時差:
hive> select create_time,
(hour(from_unixtime(unix_timestamp(),'yyyy-MM-dd HH:mm:ss'))-
hour(create_time)+(datediff(from_unixtime(unix_timestamp(),
'yyyy-MM-dd HH:mm:ss'), create_time))*24) as hour_dValue