天天看點

impala中常用日期函數

擷取目前日期

select current_timestamp()和now()等價

得到這周是這年的第幾周

weekofyear() 1-53周

eg:

#查找官網周活躍使用者:
select weekofyear(opetime),count(distinct opeuserid) 
from  platform_kudu.visitlog 
where opeuserid is not null and page like '%.3vjia.com/%' and opetime<='2019-12-29' and opetime>='2019-11-29'
group by weekofyear(opetime)
           
#新注冊使用者周留存
select  weekofyear(regdate),count(distinct userid) from
 syscore_kudu.users t1
 where regdate>='2019-11-01 00:00:00' and 
 (select count(*)  from  3d_point_kudu.userinfo t2 
 where t1.userid=t2.userid and weekofyear(t1.regdate)+1=weekofyear(t2.sendtime) and year(t1.regdate)=year(t2.sendtime))>0
 group by weekofyear(regdate)
           

增加月份

add_months(timestamp date, int months)

add_months(timestamp date, bigint months)

select add_months(substr(opetime,1,10),1) from paltform_kudu.visitlog
           

增加日期

adddate(timestamp startdate, int days)

addmonth(timestamp startdate, bigint days)

eg. adddate(now(),1)

兩個時間戳/字元串之間的時間差

unix_timestamp(string datetime, string format) 3擷取的是數字

select userid,min(sendtime) min_time,max(sendtime) max_time,(unix_timestamp(max(sendtime))-unix_timestamp(min(sendtime)))/3600/24
from 3d_point_kudu.userinfo
where substr(sendtime,1,4) >= '2019'
and snedtime <= '2020-06-21 23:59:59'
group by userid
           

格式化日期

from_unixtime(bigint unixtime[, string format])

如:擷取目前日期的前兩天

一種做法:from_unixtime(unix_timestamp()-606024*2,‘yyyy-MM-dd’),目前日期時間戳減去兩天的秒數;

另一種做法:substr(regexp_replace(cast(date_sub(now(),2 as string),’-’),1,8)),這個是 時間格式 string的處理方法

date_sub():減天數

日期轉化操作

轉換成date

字元串轉換成timestamp格式

日期的加減

目前日期+7天

目前日期減去一個月

unixtime轉換成yyyymmdd格式

#目前日期轉換成yyyy-mm-dd格式
select from_unixtime(unix_timestamp(),'yyyy-mm-dd')
           

日期轉字元串

目前日期加7天,并轉換成yyyy-mm-dd格式

字元串轉日期

将字元串日期轉化成yyyy-mm-dd格式

得到小時

hour()

增加小時

hours_add()

減少小時

hours_sub()

得到月份

month()

得到年

year()

上一篇: impala常用