使用Hive进行数据计算免不了要用到日期相关的函数,常用的就两种,但是一旦遇到不常用的就又开始面向Google编程了,于是在此总结下,方便查阅。

unix_timestamp()

该函数返回当前时区的时间戳,是比较常用的函数。

1
2
3
select unix_timestamp();

1563033600

unix_timestamp(string date)

该函数返回指定日期的时间戳,是比较常用的函数。

1
2
3
select unix_timestamp('2019-07-14 00:00:00');

1563033600

注意,这里的date只能是yyyy-MM-dd HH:mm:ss的格式。

unix_timestamp(string date,string pattern)

该函数返回指定格式日期的时间戳,是比较常用的函数。

1
2
3
select unix_timestamp('2019-07-14','yyyy-MM-dd');

1563033600

from_unixtime(bigint unixtime,string format)

该函数返回时间戳对应的日期格式

1
2
3
select from_unixtime(unix_timestamp(),'yyyy-MM-dd');

2019-07-14

这里的第一个参数unixtime为到秒级的时间戳,不是毫秒级的。

to_date(string date)

返回时间字段中的日期部分

1
2
3
select to_date('2019-07-14 22:00:00')

2019-07-14

year(string date)

返回时间字段中的年,参数dateyyyy-MM-dd或者yyyy-MM-dd HH:mm:ss

1
2
3
select year(‘2019-07-14 22:00:00’)

2019

month(string date)

返回时间字段中的月,参数dateyyyy-MM-dd或者yyyy-MM-dd HH:mm:ss,返回值范围是1-12 不是01-12。

1
2
3
select month(‘2019-07-14 22:00:00’)

7

或者

1
2
3
select month('2019-07-14')

7

day(string date)

返回时间字段中当月的第几日(dayOfMonth),参数dateyyyy-MM-dd或者yyyy-MM-dd HH:mm:ss,返回值范围是1-31 不是01-31。

1
2
3
select day('2019-07-14 22:00:00');

14

hour(string date)

返回日期中的小时,参数只能是yyyy-MM-dd HH:mm:ss格式,返回值范围是0-23

1
2
3
select hour('2019-07-14 22:30:00');

22

minute(string date)

返回日期中的分钟,参数只能是yyyy-MM-dd HH:mm:ss格式,返回值范围是0-59

1
2
3
select minute('2019-07-14 22:30:00');

30

second(string date)

返回日期中的分钟,参数只能是yyyy-MM-dd HH:mm:ss格式,返回值范围是0-59

1
2
3
select second('2019-07-14 22:01:04');

4

weekofyear(string date)

返回时间字段是本年的第多少周

1
2
3
select weekofyear('2019-07-14 22:00:00');

28

datediff(string enddate,string begindate)

返回enddate与begindate之间的时间差的天数 (enddate - begindate),注意是第一个参数-第二个参数

1
2
3
select datediff('2019-07-14','2019-07-01');

13

date_add(string date,int days)

返回date增加days天后的日期,引申意为几天后

1
2
3
select date_add('2019-07-01',13);

2019-07-14

date_sub(string date,int days)

返回date减少days天后的日期 ,引申意为几天前

1
2
3
select date_sub('2019-07-14',13);

2019-07-01

计算某一个日期属于星期几

1
2
3
SELECT IF(pmod(datediff('2019-07-14', '1920-01-01') - 3, 7)='0', 7, pmod(datediff('2019-07-14', '1920-01-01') - 3, 7)); 

7

计算指定日期上个月的第一天和最后一天

1
2
3
select trunc(add_months('2019-07-14',-1),'MM');

2019-06-01

或者

1
2
3
select concat(substr(add_months(from_unixtime(unix_timestamp(),'yyyy-MM-dd'),-1),1,7),'-01'); 

2019-06-01

第二个会产生Map的任务执行。

最后一天:

1
2
3
select date_sub(trunc('2019-07-14','MM'),1);

2019-06-30