天天看点

hive hql 时间函数 练习

时间函数

常见函数

from_unixtime(bigint unixtime,[string format]): 时间戳转日期函数,
unix_timestamp([string date]): 转换成时间戳,然后转换格式为“yyyy-MM-dd HH:mm:ss“的日期
到UNIX时间戳。如果转化失败,则返回0,返回bigint类型
to_date(string timestamp): 将时间戳转换成日期,默认格式为2011-12-08 10:03:01
year() : 将时间戳转换成年,默认格式为2011-12-08 10:03:01
month() : 将时间戳转换成月,默认格式为2011-12-08 10:03:01
hour() : 将时间戳转换成小时,默认格式为2011-12-08 10:03:01
day(string date) : 将时间戳转换成天,默认格式为2011-12-08 10:03:01
date_diff(string enddate, string startdate) : 日期比较函数,反回结束日期减去开始日期的
天数
date_sub(string startdate, int days) : 日期减少函数,返回开始日期减少days天后的日期字符
串
date_add(string startdate, int days) : 日期增加函数,返回开始日期增加days天后的日期字符
串
last_day(string date) : 返回该月的最后一天的日期,可忽略时分秒部分(HH:mm:ss)。
last_day(string date)返回string类型的值。
next_day(string date,string x) : 返回下一个星期x的日期(x为前两英文星期前两位或者全写
MONDAY),返回字符串。 
current_date() : 获取当天的日期,返回字符串,没有任何的参数。
current_timestamp() : 获取当前的时间戳
           

时间戳函数

unix_timestamp,from_unixtime

获取当前时间戳:
获取"2019-07-31 11:57:25"对应的时间戳:
获取"2019-07-31 11:57"对应的时间戳:
获取时间戳:1564545445所对应的日期和时分秒:
获取时间戳:1564545446所对应的日期和小时(yyyy/MM/dd HH): 
           
SELECT unix_timestamp("2019-07-31 11:57:25","yyyy-MM-dd HH:mm:ss") ;
SELECT unix_timestamp("2019-07-31 11:57","yyyy-MM-dd HH:mm") ;
SELECT from_unixtime(1564545445,"yyyy-MM-dd HH:mm:ss"); 
SELECT from_unixtime(1564545445,"yyyy/MM/dd HH"); 
           

时间格式转换

yyyyMMdd -> yyyy-MM-dd

数据
t1表 
20190730 
20190731
编写sql实现如下的结果: 
2019-07-30 
2019-07-31
           
SELECT from_unixtime(unix_timestamp(dt,"yyyyMMdd"),"yyyy-MM-dd") 
FROM dt
;