Hive內(nèi)置函數(shù)之時間函數(shù)

零、生產(chǎn)常用組合方式

(0.1)離線數(shù)倉獲取昨天的日期作為分區(qū),格式y(tǒng)yyyMMdd

regexp_replace(date_sub(from_unixtime(unix_timestamp(),'yyyy-MM-dd'),1) ,'-','')

或者

date_format(date_sub(from_unixtime(unix_timestamp(),'yyyy-MM-dd'),1),'yyyyMMdd')

一、源碼部分

Hive的函數(shù)類為:org.apache.hadoop.hive.ql.exec.FunctionRegistry

二、常用時間函數(shù)

對于函數(shù),除了知道怎么用,還需要知道返回值是什么類型,這里給出官方文檔,文檔中給出了函數(shù)的返回值類型

官方文檔見:https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

(2.1)from_unixtime(bigint unixtime[, string format])

時間戳轉(zhuǎn)字符串

示例:

select from_unixtime(1591627588); --?2020-06-08 22:46:28

select from_unixtime(1591627588,'yyyyMMddHHmmss'); --?20200608224628


(2.2)unix_timestamp()、unix_timestamp(string date)、unix_timestamp(string date, string pattern)

時間字符串轉(zhuǎn)時間戳

示例:

select unix_timestamp('2020-06-08 22:50:00'); --?1591627800

select unix_timestamp('20200608225000','yyyyMMddHHmmss'); --?1591627800


(2.3)to_date(string timestamp)

時間字符串抽取日期

示例:

SELECT to_date('2009-07-30 04:17:52'); --?2009-07-30


(2.4)year(string date)、month(string date)、day(string date)、hour(string date)、minute(string date)、second(string date)

時間字符串抽取日期

這些函數(shù)是差不多的,都是從一個時間字符串中抽取出某個特定的時間字段。具有相同功能的還有extract(field FROM source)函數(shù)

示例:

SELECT day('2009-07-29 20:30:40'); -- 29

SELECT minute('2009-07-29 20:30:40'); -- 30


(2.5)date_add(date/timestamp/string?startdate, tinyint/smallint/int days)、date_sub(date/timestamp/string?startdate, tinyint/smallint/int days)

時間加減

這兩個功能是類似的

示例:

SELECT date_add('2009-07-30 20:50:59', 1); --?2009-07-31


(2.6)datediff(string enddate, string startdate)

計算日期間隔

截圖中結(jié)果是錯誤的,應(yīng)該為-1。

示例:

SELECT datediff('2009-06-30', '2009-07-02'); --?-2

SELECT datediff('2009-07-30', '2009-07-28'); -- 2


(2.7)current_date、current_timestamp

這兩個函數(shù)使用desc function extended 查看會報錯

示例:

獲取當(dāng)前日期或時間


(2.8)date_format(date/timestamp/string ts, string fmt)

時間格式化為指定格式

示例:

SELECT date_format('2015-04-08', 'yyyyMMdd'); --?20150408

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容