Hive数据类型:日期相关函数

1.UNIX时间戳转换为日期:

1
2
3
4
5
6
7
8
9
10
11
12
>select from_unixtime(1512388945,'yyyyMMdd')
>20171204

>select from_unixtime(1512388945,'yyyy-MM-dd HH:mm:ss')
>2017-12-04 20:02:25

>select from_unixtime(1512388945,'yyyy-MM-dd')
>2017-12-04

--'yyyy-MM-dd HH:mm:ss'为默认日期格式
>select from_unixtime(1512388945)
>2017-12-04 20:02:25

2.获取当前UNIX时间戳

1
2
3
4
5
6
>select unix_timestamp()
>1512388945

--获取当前时间
>select from_unixtime(unix_timestamp())
>2017-12-04 20:03:47

3.日期转UNIX时间戳

1
2
3
4
5
6
7
8
9
10
11
12
13
>select unix_timestamp('2017-12-04 20:03:47')
>1512388945

--如果后面只有date参数,date的形式必须为'yyyy-MM-dd HH:mm:ss'的形式
>select unix_timestamp('2017-12-04')
>NULL

--指定日期格式的时间戳
>select unix_timestamp('20171204 20:03:47','yyyyMMddHH:mm:ss')
>1512388945

>select unix_timestamp('20171204','yyyyMMdd')
>1512316800

4.日期时间转日期

1
2
>select to_date('2017-12-04 20:03:47')
>2017-12-04

5.日期转年

1
2
3
4
5
>select year('2017-12-04 20:03:47')
>2017

>select year('2017-12-04')
>2017

6.日期转月

1
2
3
4
5
>select month('2017-12-04 20:03:47')
>12

>select month(''2017-12-04')
>12

7.日期转天

1
2
3
4
5
>select day('2017-12-04 20:03:47')
>4

>select day('2017-12-04')
>4

8.日期转小时

1
2
>select hour('2017-12-04 20:03:47')
>20

9.日期转分钟

1
2
>select minute('2017-12-04 20:03:47')
>3

10.日期转秒

1
2
>select second('2017-12-04 20:03:47')
>47

11.日期转周

1
2
3
4
5
6
7
8
9
--默认周一至周日为自然周
>select weekofyear('2017-01-08 10:03:01')
>1

>select weekofyear('2017-01-01 10:03:01')
>52

>select weekofyear('2017-01-09 10:03:01')
>2

12.两个日期相隔的天数

1
2
3
--第一个日期减去第二个日期,自动忽略时分秒
>select datediff('2017-12-01 10:11:21','2017-12-04 11:11:21')
>-3

13.日期增加函数

1
2
3
--自动忽略时分秒
>select date_add('2017-12-08 10:03:01',10)
>2017-12-18

14.日期减少

1
2
3
--自动忽略时分秒
>select date_sub('2017-12-08 10:03:01',10)
>2017-11-28