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;
1

h.日期转周函数: weekofyear语法:   weekofyear (string date)
返回值: int
说明: 返回日期在当前的周数。
举例:
hive> select weekofyear(’2011-12-08 10:03:01′) from dual;
49

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个小时!

Logo

大数据从业者之家,一起探索大数据的无限可能!

更多推荐