hive中日期格式转换
日期时间格式大致分成时间戳和日期时间格式互转,字符串转化成日期时间格式,日期格式之间的转化
一、时间戳和日期互转
1、unix_timestamp函数,日期转时间戳
- 当函数参数为空时,返回当前时间戳。
select unix_timestamp() ---1571282494
- 不输入时间格式,默认’yyyy-MM-dd HH:mm:ss’格式
select unix_timestamp('2019-09-11 23:23:12') --1568215392
select unix_timestamp('2019-09-11') ---返回null
- 正常情况下使用自定义格式,当输入类型和格式匹配返回正确值,否则返回null
select unix_timestamp('2019-09-11','yyyy-mm-dd') --1547136540
2、from_unixtime时间戳转日期
- 默认格式 ‘yyyy-MM-dd HH:mm:ss’,不能为空值,可以指定特定格式
select from_unixtime(1547136540) --2019-01-11 00:09:00
select from_unixtime(1547136540,'HH:mm:ss') --00:09:00
3、经常使用的用法:日期格式之间的互换
把20190911转化2019/09/11
select from_unixtime(unix_timestamp('20190911','yyyyMMdd'),'yyyy/MM/dd')
4、日期格式yyyy-MM-dd格式转化成其他格式
date_format主要针对yyyy-MM-dd的时间格式转化成其他格式的日期字符串。
select date_format('2019-09-11','yyyy/MM/dd')
二、其他时间函数,针对’yyyy-MM-dd HH:mm:ss’
1、to_date函数,返回日期时间中的日期部分
通常只能应用于’yyyy-MM-dd HH:mm:ss’格式的日期时间截取
select to_date('2019-09-11 12:10:21') --2019-09-11
2、year, month, day, hour, minute,second函数
select second('2019-09-11 12:10:21') ---21
3、日期转周函数weekofyear
select weekofyear('2011-12-08 10:03:01') from dual;--49
三、时间函数运算
1、datediff 日期比较函数,默认格式’yyyy-MM-dd HH:mm:ss’
select datediff('2019-01-11','2019-08-11') --输出-212
2、时间增加函数 date_add
select date_add('2012-12-08',10)
3、时间减少函数 date_sub
select date_sub('2019-09-11',10)
4、获取两个时间的相差月份数
select floor(months_between('2018-07-01','2018-02-04')) from default.dual
四、获取当前时间
select current_date() --2019-10-17 获取日期格式
select unix_timestamp(). --1571285121 获取时间戳