hive中时间以字符串格式表达的相关计算

一、步骤:

  • 字符串转变为时间戳(unix_timestamp()函数)
  • 在将时间戳转换为标准时间格式(from_unixtime()函数)
  • 最后使用计算函数进行相应的计算(add_months()函数)
select add_months(from_unixtime(unix_timestamp(create_date, 'yyyy-MM-dd'),'yyyy-MM-dd'),-12) from dim_date_df limit 5;
计算环比日期(一年前的同一天)

二、涉及到的函数:

1、unix_timestamp():

select unix_timestamp('2018-08-15 14:22:00'); 
select unix_timestamp('2018-08-15 14:22:00','yyyy-MM-dd HH:mm:ss');
select unix_timestamp('20180815 14:22:00','yyyyMMdd HH:mm:ss'); 
image.png

2、from_unixtime()

select from_unixtime(1534314120); 
select from_unixtime(1534314120,'yyyyMMdd'); 
select from_unixtime(1534314120,'yyyy-MM-dd HH:mm:ss'); 
image.png

3、add_months()

select add_months(from_unixtime(1534314120,'yyyy-MM-dd'),2);
select add_months(from_unixtime(1534314120,'yyyy-MM-dd'),-2);
image.png

三、与mysql的一点区别

1、获取系统时间

可以看到 now()函数是invalid的。

select unix_timestamp();

当然,得到的是时间戳。


image.png

2.日期(天数)增加和减少: date_add/date_sub(string startdate,int days)

在mysql中需要加上单位,表明要对年月日还是时分秒进行计算。而hive中不需要加单位,并且只能对天进行计算。

select date_add('2018-08-15',1) ;    
select date_sub('2018-08-15',1) ;    
select date_add('2018-08-15',15) ; 
select date_sub('2018-08-15',17) ; 
image.png

四、补充函数

  • 查询当前系统时间(包括毫秒数): current_timestamp;
  • 查询当月第几天: dayofmonth(current_date);
  • 月末: last_day(current_date)
  • 当月第1天: date_sub(current_date,dayofmonth(current_date)-1)
  • 下个月第1天: add_months(date_sub(current_date,dayofmonth(current_date)-1),1)

你可能感兴趣的:(hive中时间以字符串格式表达的相关计算)