数据蛙数据分析每周作业

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

2020-11-25  本文已影响0人  我住永安当

一、步骤:

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

四、补充函数

上一篇 下一篇

猜你喜欢

热点阅读