在hive中有计算两个日期的天数差的函数:
日期差值:datediff(结束日期,开始日期),返回结束日期减去开始日期的天数。
1 select datediff(CURRENT_DATE,\'2019-01-01\') as datediff; 2 +-----------+--+ 3 | datediff | 4 +-----------+--+ 5 | 445 | 6 +-----------+--+
在实际使用过程中,大多数时候日期的存储格式是\'yyyyMMdd\',那么可以变换日期格式为\'yyyy-MM-dd\'之后再使用函数datediff:
在hive中没有可以直接转换的函数,需要先经过中间状态:时间戳格式
先将日期由\'yyyyMMdd\'格式转换为时间戳:
1 select unix_timestamp(\'20160816\',\'yyyyMMdd\'); 2 +-----------+--+ 3 | datediff | 4 +-----------+--+ 5 | 1471276800 | 6 +-----------+--+
再将时间戳转换为\'yyyy-MM-dd\'格式:
1 select from_unixtime(1471276800,\'yyyy-MM-dd\'); 2 +-----------+--+ 3 | datediff | 4 +-----------+--+ 5 | 2016-08-16 | 6 +-----------+--+
合并使用:
1 select from_unixtime(unix_timestamp(\'20160816\',\'yyyyMMdd\'),\'yyyy-MM-dd\') ; 2 +-----------+--+ 3 | datediff | 4 +-----------+--+ 5 | 2016-08-16 | 6 +-----------+--+
之后就可以愉快的计算日期差啦~~
附赠其他日期转换:
固定日期转换成时间戳
select unix_timestamp(\'2016-08-16\',\'yyyy-MM-dd\') --1471276800
select unix_timestamp(\'20160816\',\'yyyyMMdd\') --1471276800
select unix_timestamp(\'2016-08-16T10:02:41Z\', "yyyy-MM-dd\'T\'HH:mm:ss\'Z\'") --1471312961
16/Mar/2017:12:25:01 +0800 转成正常格式(yyyy-MM-dd hh:mm:ss)
select from_unixtime(to_unix_timestamp(\'16/Mar/2017:12:25:01 +0800\', \'dd/MMM/yyy:HH:mm:ss Z\'))
select from_unixtime(to_unix_timestamp(\'16/Mar/2017:12:25:01 +0800\', \'dd/MMM/yyy:HH:mm:ss Z\'))
时间戳转换程固定日期
select from_unixtime(1471276800,\'yyyy-MM-dd\') --2016-08-16
select from_unixtime(1471276800,\'yyyyMMdd\') --20160816
select from_unixtime(1471312961) -- 2016-08-16 10:02:41
select from_unixtime( unix_timestamp(\'20160816\',\'yyyyMMdd\'),\'yyyy-MM-dd\') --2016-08-16
select date_format(\'2016-08-16\',\'yyyyMMdd\') --20160816
select from_unixtime(1471276800,\'yyyy-MM-dd\') --2016-08-16
select from_unixtime(1471276800,\'yyyyMMdd\') --20160816
select from_unixtime(1471312961) -- 2016-08-16 10:02:41
select from_unixtime( unix_timestamp(\'20160816\',\'yyyyMMdd\'),\'yyyy-MM-dd\') --2016-08-16
select date_format(\'2016-08-16\',\'yyyyMMdd\') --20160816