hive计算日期差

首先,hive本身有一个UDF,名字是datediff。我们来看一下这个日期差计算的官方描述,(下面这个是怎么出来的):

hive> desc function extended datediff;
OK
datediff(date1, date2) - Returns the number of days between date1 and date2
date1 and date2 are strings in the format 'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd'. The time parts are ignored.If date1 is earlier than date2, the result is negative.
Example:
   > SELECT datediff('2009-30-07', '2009-31-07') FROM src LIMIT 1;

从上面的描述可以看出datediff用法很简单,就是datediff('日期1','日期2'),其中日期是有格式的,目前支持以下两种格式:

yyyy-MM-dd HH:mm:ss
yyyy-MM-dd

但是,看上面的显示 hive function里对datediff的example有问题,2009-30-07应该为2009-07-30,实际上这个udf 还支持2009-7-30这种格式。这里我的一个列子:

SELECT datediff('2013-10-15', '2013-9-15') FROM words LIMIT 1;

如果我的日期是2013/10/15这样的,该这么办?这时候可以用hive的regexp_replace 这个UDF。示例如下:

SELECT datediff(regexp_replace('2013/10/15', "/", "-"),regexp_replace('2013/9/15', "/", "-")) FROM words LIMIT 1;

 程序猿必读

原文地址:https://www.cnblogs.com/longzhongren/p/4331043.html