類似於mysql,hive中也有處理日期和時間的方法。
1. 日期轉時間戳:unix_timestamp
select unix_timestamp('2020/03/25 15:54:24', 'yyyy/MM/dd HH:mm:ss') from db_name.tb_name # 如果不寫第二個格式參數,默認格式是 yyyy-MM-dd HH:mm:ss,如果不一致,會返回null
2. 時間戳轉日期:from_unixtime
select from_unixtime(cast(1572316836 as bigint),'yyyy/MM/dd HH:mm:ss') select from_unixtime(cast(createtime/1000 as bigint),'yyyy/MM/dd HH:mm:ss') from db_name.tb_name #createtime為時間戳列名,第二個參數指定轉換后的格式
3. to_date 獲取日期
select to_date('2020/03/25 15:54:24', 'yyyy/MM/dd HH:mm:ss') from db_name.tb_name # 第二個參數是格式,如果不寫,默認是 yyyy-MM-dd HH:mm:ss select to_date('2020/03/25 15:54:24', 'yyyy/MM/dd HH:mm:ss')
4. datediff 求日期差
select datediff('2020-03-25', '2020-03-31') from db_name.tb_name # 第一個參數是end_date,第二個是start_date,表示前面的日期減去后面的差值
5. year(submission_time),month(submission_time),day(submission_time),hour(submission_time),minute(submission_time),second(submission_time) 用於從日期時間字符串獲取年、月、日、時、分、秒
select year('2020-03-25 12:25:30') from db_name.tb_name
6. date_add:求日期向后推n天
select date_add('2020-03-25', 10) from db_name.tb_name limit 10
7. date_sub:求日期向前推n天
select date_sub('2020-03-25', 10) from db_name.tb_name limit 10
8. dayofweek:求周幾(星期),周日值是1,周一值是2
select dayofweek('2020-04-06') from db_name.tb_name limit 10
9. 本年第幾周:weekofyear
select weekofyear('2020-04-06') from db_name.tb_name limit 10
10. 下周幾:next_day
select next_day('2020-04-06','Mon') #下周一
11. 月最后一天:last_day
select last_day('2020-04-06')
12. 年、月的第一天
select trunc('2020-04-06','MM') #月第一天 select trunc('2020-04-06','YY') #年第一天
13. 求季度
select lpad(ceil(month('2020-04-06')/3),2,0) # lpad是補齊函數,第一個是要補的字符串,第二個參數是補成多長的值,第三個是用什么字符補
#
參考: