Impala常用日期函式

2021-10-23 19:46:38 字數 2990 閱讀 7315

--當前時間戳

--當前時間戳相對於 linux epoch 的秒數

unix_timestamp() , 不帶引數, 則返回 '1970-01-01 00:00:00' utc 到現在的秒數

-- 轉換到相對於 linux epoch 的秒數

unix_timestamp(now()+ interval 3 days), 如果傳入 timestamp 引數, 返回該時間戳相對於 linux epoch 的秒數

unix_timestamp(string datetime, string format), 還支援傳入時間字串, 返回值還是相對於 linux epoch 的秒數

-- 將秒數轉換到字串

from_unixtime(int, 'yyyy/mm/dd hh:mm'), 將指定的時間戳,格式化為字串. 時間戳引數應該是秒數格式, 所以該引數需要用 unix_timestamp() 包一下.

注意月份和分鐘對應的格式字串, 常用的格式有 "yyyy-mm-dd hh:mm:ss.ssssss", "dd/mm/yyyy hh:mm:ss.ssssss", "mmm dd, yyyy hh.mm.ss (ssssss)"

-- 將時間戳轉換為日期字串

to_date(timestamp) , 將指定時間戳轉換為日期字串, 日期格式為 yyyy--mm-dd .

-- 將秒數轉換成時間戳

to_timestamp(bigint unixtime)

-- 將字串轉換成時間戳

to_timestamp(string date, string pattern)

說明: impala 沒有直接將時間戳轉換為字串的函式, 所以經常的寫法是: from_unixtime(unix_timestamp( t1 ),'yyyymmdd hh:mm')

-- 時間戳取整

impala 2.11 之前的取整當前時間的寫法:

select trunc(now(), 'year') --取整到年份, 得到當年 1 月 1 日 0 點 0 分

select trunc(now(), 'month') --取整到月份, 得到當月 1 日 0 點 0 分

select trunc(now(), 'dd') --取整到日期, 得到當天 0 點 0 分

select trunc(now(), 'day') --取整到星期, 得到本星期第一天的 0 點 0 分

select trunc(now(), 'hh24') --取整到小時, 得到當前小時的 0 分

select trunc(now(), 'mi') --取整到分鐘, 得到當前分鐘 0 秒

-- 時間戳提取

date_part('year', now())

extract(now(), 'year')

extract(year from now())

-- 兩個時間戳比較

datediff(timestamp enddate, timestamp startdate) ,相差多少天, 精度是天

timestamp_cmp(now() + interval 70 minutes, now()), 比較兩個時間戳的大小, 本例的結果為 1

impala 沒有好用的 timestamp_diff() 函式, 比如我們想要知道兩個時間相差多少個小時, 不能直接求出, 下面是乙個簡單的步驟:

1. 先算出乙個小時對應的秒數是多少

2. 將兩個時間都轉成秒數, 然後做差, 然後除以乙個小時的秒數.

-- 時間加減

時間戳可以直接加減 interval n days/months/years/hours/minutes .

也可以使用下面的函式:

years_add(timestamp t, int n)

years_sub(timestamp t, int n)

months_add(timestamp t, int n)

months_sub(timestamp t, int n)

days_add(timestamp t, int n)

days_sub(timestamp t, int n)

hours_add(timestamp t, int n)

hours_sub(timestamp t, int n)

minutes_add(timestamp t, int n)

minutes_sub(timestamp t, int n)

也可以用下面兩個通用的函式:

date_add(timestamp startdate, int days)

date_add(timestamp startdate, interval_expression)

date_sub(timestamp startdate, int days)

date_sub(timestamp startdate, interval_expression)

-- 月份相關的

last_day(timestamp t)

months_between(timestamp newer, timestamp older)

impala 時間日期函式全解

hive 日期函式 增加月份 add months timestamp date,int months add months timestamp date,bigint months return type timestamp usage add months now 1 增加日期 adddate ...

impala 時間函式

當前時間戳 now current timestamp 當前時間戳相對於 linux epoch 的秒數 unix timestamp 不帶引數,則返回 1970 01 01 00 00 00 utc 到現在的秒數 轉換到相對於 linux epoch 的秒數 unix timestamp now ...

Impala 條件函式

支援的條件函式列表 case 標準通用的函式 coalesce 標準通用函式 decode oracle和impala專用函式 if impala和mysql的函式 ifnull impala和mysql的函式 isfalse isnotfalse isnottrue isnull istrue n...