1. 程式人生 > 其它 >hive時間函式

hive時間函式

to_date:日期時間轉日期函式
select to_date('2015-04-02 13:34:12');
輸出:2015-04-02

from_unixtime:轉化unix時間戳到當前時區的時間格式
select from_unixtime(1323308943,’yyyyMMdd’);
輸出:20111208

unix_timestamp:獲取當前unix時間戳
select unix_timestamp();
輸出:1430816254
select unix_timestamp('2015-04-30 13:51:20');
輸出:1430373080

year:返回日期中的年
select year('2015-04-02 11:32:12');
輸出:2015

month:返回日期中的月份
select month('2015-12-02 11:32:12');
輸出:12

day:返回日期中的天
select day('2015-04-13 11:32:12');
輸出:13

hour:返回日期中的小時
select hour('2015-04-13 11:32:12');
輸出:11

minute:返回日期中的分鐘
select minute('2015-04-13 11:32:12');
輸出:32

second:返回日期中的秒
select second('2015-04-13 11:32:56');
輸出:56

weekofyear:返回日期在當前週數
select weekofyear('2015-05-05 12:11:1');
輸出:19

datediff:返回開始日期減去結束日期的天數
select datediff('2015-04-09','2015-04-01');
輸出:8

date_sub:返回日期前n天的日期
select date_sub('2015-04-09',4);
輸出:2015-04-05

date_add:返回日期後n天的日期
select date_add('2015-04-09',4);
輸出:2015-04-13

from_unixtime+ unix_timestamp Hive中yyyymmdd和yyyy-mm-dd日期之間的切換
思想:先轉換成時間戳,再由時間戳轉換為對應格式。
--20171205轉成2017-12-05
select from_unixtime(unix_timestamp('20171205','yyyymmdd'),'yyyy-mm-dd') from dual;

--2017-12-05轉成20171205
select from_unixtime(unix_timestamp('2017-12-05','yyyy-mm-dd'),'yyyymmdd') from dual;


Hive中取最近30天資料
datediff(CURRENT_TIMESTAMP ,gmt_create)<=30
1
Hive中 兩個日期相差多少小時
select (unix_timestamp('2018-05-25 12:03:55') - unix_timestamp('2018-05-25 11:03:55'))/3600
輸出:1

Hive中 兩個日期相差多少分鐘
select (unix_timestamp('2018-05-25 12:03:55') - unix_timestamp('2018-05-25 11:03:55'))/60

輸出:60


hive 計算某一個日期屬於星期幾,如2018-05-20 是星期日
SELECT IF(pmod(datediff('2018-05-20', '1920-01-01') - 3, 7)='0', 7, pmod(datediff('2018-05-20', '1920-01-01') - 3, 7))
輸出:7

hive返回上個月第一天和最後一天
--上個月第一天
select trunc(add_months(CURRENT_TIMESTAMP,-1),'MM')

select concat(substr(add_months(from_unixtime(unix_timestamp(),'yyyy-MM-dd'),-1),1,7),'-01');

--上個月最後一天
select date_sub(trunc(CURRENT_TIMESTAMP,'MM'),1);