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