Hive:处理时间的函数

UNIX时间戳概念

从格林尼治时间1970-01-01 00:00:00开始,到现在经过的秒数。
时间戳是一个32位的整数(所以UNIX时间戳最多表示到2037年左右)。

因为UNIX时间戳只是一个秒数,一个UNIX时间戳在不同时区看来,时间是不同的。
如UNIX时间戳0,在0时区看来是1970-01-01 00:00:00,在东八区看来是1970-01-01 08:00:00。

补充一点:由于spark sql中TimestampType类型表示的是java.sql.Timestamp类型,而后者的构造函数接受的参数是以毫秒为单位的,所以注意进行转换。
如unix_timestamp函数返回的值如果要直接用cast转为时间戳类型,记得要乘以1000:

select cast(unix_timestamp()*1000 as timestamp);
2018-07-27 10:00:31

Hive中处理时间相关的函数

-- 返回UNIX时间戳代表的(当前时区的)时间,默认格式如下。
select from_unixtime(1);
1970-01-01 08:00:01
select from_unixtime(1 ,'yyyyMMdd hh:mm:ss');
19700101 08:00:01

-- 获取当前时间的UNIX时间戳(时区无关的),返回值bigint(对应spark中Long)。
select unix_timestamp();
1532655119
--转换(当前时区)时间字符串到UNIX时间戳,默认字符串格式如下。
select unix_timestamp('1970-01-01 08:00:01');
1
select unix_timestamp('19700101 08:00:01','yyyyMMdd HH:mm:ss');
1

其他日期函数

-- 获取日期部分
select to_date('2017-08-04 11:40:03');
2017-08-04
-- 同样还有返回年、月、日、时、分、秒、周的函数
select year('2017-08-04 11:40:03');
2017
select year('2017-08-04');
2017

select month('2017-08-04 11:40:03');
8
select month('2017-08-04');
8

select day('2017-08-04 10:03:01');
4
select day('2017-08-04');
4

select hour('2017-08-04 11:40:01');
11
select hour('11:40:01');
11


select minute('2017-08-04 11:40:01');
40

select second('2017-08-04 11:40:01');
1

select weekofyear('2017-08-04 11:40:01');
31

--返回两个日期相隔天数
select datediff('2017-08-04','2015-05-09');
818

--增加天数
select date_add('2017-08-04',10);
2017-08-14
--减少天数
select date_sub('2017-08-04',10);
2017-07-25
posted @ 2019-01-03 16:15  xuejianbest  阅读(1521)  评论(0编辑  收藏  举报