hive時間操作函數:獲取小時差.天數差

https://blog.csdn.net/wrty1993/article/details/78548312

1.首先hive獲取當前時間的函數與sql 不一樣
sql是:now();

(1) hive有一個獲得當前時區的UNIX時間戳:unix_timestamp
語法: unix_timestamp()
返回值: bigint
說明: 獲得當前時區的UNIX時間戳
舉例:
hive> select unix_timestamp() from test;
1453261615

(2)我們需要的不是時間戳而是具體的當前時間:from_unixtime

語法:   from_unixtime(bigint unixtime[, string format])
舉例:
hive > select from_unixtime(unix_timestamp(),'yyyy-MM-dd HH:mm:ss') from test;
    2017-11-16 09:43:35

(3) 獲取數據創建時間與當前時間的時間差:datediff

desc function extended datediff;
OK
datediff(date1, date2) - Returns the number of days between date1 and date2
date1 and date2 are strings in the format ‘yyyy-MM-dd HH:mm:ss’ or ‘yyyy-MM-dd’. The time parts are ignored.If date1 is earlier than date2, the result is negative.
Example:
SELECT datediff(‘2009-30-07’, ‘2009-31-07’) FROM src LIMIT 1;

datediff的用法:datediff(‘日期1’,’日期2’),其中日期是有格式的,目前支持以下兩種格式:

‘yyyy-MM-dd HH:mm:ss’
‘yyyy-MM-dd’

舉例:獲取表創建時間與當前時間的之間差(day)

hive > select create_time ,datediff(from_unixtime(unix_timestamp(),’yyyy-MM-dd HH:mm:ss’), create_time) from test;
2017-11-10 09:43:35 6

結果就是:當前時間是2017-11-16 與create_time的11-10之間差了6天,輸出6;

(4)那我們要獲得小時差呢?
(4.1) 有一系列獲取日期轉年月日小時周的方法:

a. 日期時間轉日期函數: to_date語法: to_date(string timestamp) 返回:string
hive> select to_date(’2011-12-08 10:03:01′) from dual;
2011-12-08

 b. 日期轉年函數: year語法:   year(string date)
hive> select year(’2011-12-08 10:03:01′) from dual;
2011

c. 日期轉月函數: month語法: month (string date)
hive> select month(’2011-08-08′) from dual;
8

d.日期轉天函數: day語法: day   (string date)
hive> select day(’2011-12-08 10:03:01′) from dual;
8

e.日期轉小時函數: hour語法: hour (string date)
hive> select hour(’2011-12-08 10:03:01′) from dual;
10

f.日期轉分鐘函數: minute語法: minute   (string date)
hive> select minute(’2011-12-08 10:03:01′) from dual;
3

g.日期轉秒函數: second語法: second (string date)
hive> select second(’2011-12-08 10:03:01′) from dual;
 

h.日期轉周函數: weekofyear語法:   weekofyear (string date)
返回值: int
說明: 返回日期在當前的週數。
舉例:
hive> select weekofyear(’2011-12-08 10:03:01′) from dual;

i.日期比較函數: datediff語法: datediff(string enddate, string startdate)
返回值: int
說明: 返回結束日期減去開始日期的天數。
舉例:
hive> select datediff(’2012-12-08′,’2012-05-09′) from dual;
213

j.日期增加函數: date_add語法:   date_add(string startdate, int days)
返回值: string
說明: 返回開始日期startdate增加days天后的日期。
舉例:
hive> select date_add(’2012-12-08′,10) from dual;
2012-12-18

k.日期減少函數: date_sub語法: date_sub (string startdate, int days)
返回值: string
說明: 返回開始日期startdate減少days天后的日期。
舉例:
hive> select date_sub(’2012-12-08′,10) from dual;
2012-11-28

(4.2)   所以我們利用其中的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 from test;
   2017-11-10 09:43:35   145   

因爲當前時間是2017-11-16 10:36:42 中間差了145個小時!
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章