日期转换hivesql

[转] String to Date conversion in hive - 在 Hive 中各种字符串转换成日期格式
【hive 日期函数】Hive常用日期函数整理
Hive日期格式转换用法
整理有参考上述文章,仅供学习,感恩知识共享~


  • current_date:当前日期
select current_date();
--输出:2020-07-23
  • current_timestamp:当前时间戳
select current_timestamp();
--输出:2020-07-23 10:06:31.068
  • unix_timestamp:获取当前unix时间戳
select unix_timestamp('2015-04-30 13:51:20');
-- 输出:1430373080
  • from_unixtime:转化unix时间戳到当前时区的时间格式
select from_unixtime(unix_timestamp('7/23/2020','MM/dd/yyyy'))
-- 输出2020-07-23 00:00:00

select from_unixtime(unix_timestamp('7/23/2020','MM/dd/yyyy'),'yyyy-MM-dd')
--输出2020-07-23

可以转化各种不同的时间格式为yyyy-MM-dd这种相对规范的格式
原始日期是什么,unix_timestamp中的日期格式就是什么,然后通过from_unixtime转换为yyyy-MM-dd!

  • to_date:日期时间转日期函数
select to_date('2020-07-23 13:34:12')
--输出2020-07-23
  • year:返回日期中的年
  • month:返回日期中的月份
  • day:返回日期中的天
  • hour:返回日期中的小时
  • minute:返回日期中的分钟
  • second:返回日期中的秒
  • weekofyear:返回日期在当前周数
select weekofyear('2020-07-23');
--输出:30
  • datediff:日期做差
select datediff('2020-07-09','2020-07-01');
--输出:8
  • date_add:返回日期后n天的日期
select date_add(current_date(),7);
--输出:2020-7-30
  • date_sub:返回日期前n天的日期
select date_sub('2020-07-09',1);
--输出:2020-07-08

比如选择未来3天过生日的人员信息

--未来7天过生日
datediff(date_add(current_date(),7),from_unixtime(unix_timestamp(concat(substr(current_date(),0,4),substr(birthday,5)),'yyyyMMdd'),'yyyy-MM-dd')) between 0 and 3;
  • trunc:返回上个月第一天和最后一天
--上个月第一天
select trunc(add_months(CURRENT_TIMESTAMP,-1),'MM')
--上月最后一天
select date_sub(trunc(CURRENT_TIMESTAMP,'MM'),1);
  • 两个日期相差多少小时
select (unix_timestamp('2020-07-235 12:03:55') - unix_timestamp('2020-07-23 11:03:55'))/3600
输出:1
  • 两个日期相差多少分钟
select (unix_timestamp('2020-07-23 12:03:55') - unix_timestamp('2020-07-23 11:03:55'))/60
输出:60
  • 计算某一个日期属于星期几,如2018-05-20 是星期日
SELECT IF(pmod(datediff('2018-05-20', '1920-01-01') - 3, 7)='0', 7, pmod(datediff('2018-05-20', '1920-01-01') - 3, 7)) 
输出:7

猜你喜欢

转载自blog.csdn.net/qq_43165880/article/details/107529406