hive的日期和时间

类似于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是补齐函数,第一个是要补的字符串,第二个参数是补成多长的值,第三个是用什么字符补

#

参考:

https://blog.csdn.net/wj1066/article/details/78795887

https://www.cnblogs.com/chenzechao/p/8621946.html

猜你喜欢

转载自www.cnblogs.com/qi-yuan-008/p/12642224.html