hive 常用日期处理函数

在工作中,日期函数是提取数据计算数据必须要用到的环节。哪怕是提取某个时间段下的明细数据也得用到日期函数。今天和大家分享一下常用的日期函数。为什么说常用呢?其实这些函数在数据运营同学手上是几乎每天都在使用的。

hive 常用日期处理函数_unix


序号

hive日期函数

函数用法

含参方式

备注

1

to_date

转化成日期

to_date('string

 time')

to_date('2023-5-20

 05:20:00')

   输出:2023-5-20

2

from_unixtime

转化unix时间戳到当前时区的时间格式

from_unixtime(bigint

 unixtime,[string format])

select

 from_unixtime(1684559640,'yyyyMMdd');

   输出:20230520

3

unix_timestamp

日期转化为unix时间戳

unix_timestamp(string

 format)

select

 unix_timestamp();

   输出:1684559640

   select unix_timestamp('2023-05-20 13:14:00');

   输出:1684559640

4

date2datekey

date格式转化成datekey

date2datekey(string

 date/time)

date2datekey('2023-05-20')

   输出:20230520

5

datekey2date

datekey格式转化为date

datekey2date(string

 datekey)

datekey2date('20230520')

   输出:2023-05-20

6

datediff

返回开始日期减去结束日期的天数

datediff(string

 enddate ,string begindate)

select

 datediff('2023-05-20','2023-05-18');

   输出:2

7

date_sub

返回日期前n天的日期

date_sub(string

 startdate,int days )

date_sub('2023-05-20',2

 )

   输出:2023-05-18

8

date_add

返回日期后n天的日期

date_add(string

 startdate,int days )

date_add('2023-05-20',2

 )

   输出:2023-05-22

9

year

返回日期中的年

year(string

 date)

year('2023-05-20

 11:32:12');

   输出:2023

10

month

返回日期中的月份

month(string

 date)

month('2023-05-20

 11:32:12');

   输出:05

11

day

返回日期中的天

day(string

 date)

day('2023-05-20

 11:32:12');

   输出:20

12

hour

返回日期中的小时

hour(string

 date)

hour('2023-05-20

 11:32:12');

   输出:11

13

minute

返回日期中的分钟

minute(string

 date)

minute('2023-05-20

 11:32:12');

   输出:32

14

second

返回日期中的秒

second(string

 date)

second('2023-05-20

 11:32:12');

   输出:12

15

weekofyear

返回日期在当前周数

weekofyear(string

 date)

weekofyear('2023-05-20

 11:32:12');

   输出:20

16

unix_timestamp

格式是timestamp,精确到秒

unix_timestamp(ymdhms2)

 - unix_timestamp(ymdhms1)


   -- 计算2个时间相差的秒数

       (unix_timestamp(time1)-unix_timestamp(time2))

   -- 同理,若是计算相差的分钟,就在以上基础再除以60,小时,天数也是同理

       (unix_timestamp(time1)-unix_timestamp(time2))/60

   -- 根据上述的函数计算后,发现有小数点,可用cast优化为以下

       cast((unix_timestamp(time1)-unix_timestamp(time2))/60 as int)

   -- 相差的秒数。

      CAST((unix_timestamp() - unix_timestamp(ymdhms))  % 60 AS int)

   -- 相差的分钟数。

      CAST((unix_timestamp() -  unix_timestamp(ymdhms)) / 60 AS int) % 60

   -- 相差的小时数。

      CAST((unix_timestamp() - unix_timestamp(ymdhms))  / (60 * 60) AS int) % 24

   -- 相差的天数。

      concat(CAST((unix_timestamp() -  unix_timestamp(ymdhms)) / (60 * 60 * 24) AS int)