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
类型,而后者的构造函数接受的参数是以毫秒为单位的,所以注意进行转换。
select cast(unix_timestamp()*1000 as timestamp);2018-07-27 10:00:31
Hive中处理时间相关的函数
-- 返回UNIX时间戳代表的(当前时区的)时间,默认格式如下。select from_unixtime(1);1970-01-01 08:00:01select 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');1select 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');2017select year('2017-08-04');2017select month('2017-08-04 11:40:03');8select month('2017-08-04');8select day('2017-08-04 10:03:01');4select day('2017-08-04');4select hour('2017-08-04 11:40:01');11select hour('11:40:01');11select minute('2017-08-04 11:40:01');40select second('2017-08-04 11:40:01');1select 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