Hive日期函数 Hive官网地址: http://hive.apache.org/ 前置:Hive查看函数使用方法 查看month相关的函数: show functions like '*month*' 查看add_months函数的用法: desc function add_months; 查看add_months函数的详细说明和例子: desc function extended add_months; 常用的日期函数 unix_timestamp() :获取当前unix的时间戳 1 select unix_timestamp(); 2 +-------------+--+ 3 | _c0 | 4 +-------------+--+ 5 | 1527917075 | 6 +-------------+--+ 7 8 select unix_timestamp('2018-06-02 20:24:35'); 9 +-------------+--+ 10 | _c0 | 11 +-------------+--+ 12 | 1527942275 | 13 +-------------+--+ from_unixtime() :转化unix时间戳到当前时区的时间,以指定格式 1 select from_unixtime(unix_timestamp(), 'yyyy-MM-dd'); 2 +-------------+--+ 3 | _c0 | 4 +-------------+--+ 5 | 2018-06-02 | 6 +-------------+--+ 7 8 select from_unixtime(1527917075, 'yyyyMMdd'); 9 +-----------+--+ 10 | _c0 | 11 +-----------+--+ 12 | 20180602 | 13 +-----------+--+ to_date() :时间转日期格式 1 select to_date(from_unixtime(unix_timestamp(), 'yyyy-MM-dd')); 2 +-------------+--+ 3 | _c0 | 4 +-------------+--+ 5 | 2018-06-02 | 6 +-------------+--+ 7 8 select to_date('2018-06'); 9 +-------+--+ 10 | _c0 | 11 +-------+--+ 12 | NULL | 13 +-------+--+ select to_date(unix_timestamp()); 会报错如下: Error: Error while compiling statement: FAILED: SemanticException [Error 10014]: Line 1:7 Wrong arguments ‘unix_timestamp’: TO_DATE() only takes STRING/TIMESTAMP/DATEWRITABLE types, got LONG (state=42000,code=10014) date_sub(start_date, num_days) - Returns the date that is num_days before start_date. 1 select date_sub('2018-06-02', 30); 2 +-------------+--+ 3 | _c0 | 4 +-------------+--+ 5 | 2018-05-03 | 6 +-------------+--+ 7 8 select date_sub('2018-06', 30); 9 +-------+--+ 10 | _c0 | 11 +-------+--+ 12 | NULL | 13 +-------+--+ 14 15 select date_sub('20180602', 30); 16 +-------+--+ 17 | _c0 | 18 +-------+--+ 19 | NULL | 20 +-------+--+ date_format(date/timestamp/string, fmt) - converts a date/timestamp/string to a value of string in the format specified by the date format fmt. 1 select date_format('2018-06-02 20:24:35', 'yyyy-MM-dd'); 2 +-------------+--+ 3 | _c0 | 4 +-------------+--+ 5 | 2018-06-02 | 6 +-------------+--+ 7 8 select date_format('2018-06-02 20:24:35', 'yyyy-MM'); 9 +----------+--+ 10 | _c0 | 11 +----------+--+ 12 | 2018-06 | 13 +----------+--+ 返回时间中的年、月、日等: 1 select year('2018-06-02 20:24:35'); 2 3 select month('2018-06-02 20:24:35'); 4 5 select day('2018-06-02 20:24:35'); 6 7 select hour('2018-06-02 20:24:35'); 8 9 select minute('2018-06-02 20:24:35'); 10 11 select second('2018-06-02 20:24:35'); 12 13 -- 返回时间在整年中的周数 14 select weekofyear('2018-06-02 20:24:35'); datediff() :返回开始日期减去结束日期的天数 1 select datediff('2018-06-02', '2018-05-21'); 2 +------+--+ 3 | _c0 | 4 +------+--+ 5 | 12 | 6 +------+--+ 7 8 -- 取最近30天数据 9 select * from dws__bill where datediff(CURRENT_TIMESTAMP, createtime) <= 30; date_add() :返回给定日期后n天的日期 1 select date_add('2018-06-02', 10); 2 +-------------+--+ 3 | _c0 | 4 +-------------+--+ 5 | 2018-06-12 | 6 +-------------+--+