hive中日期格式转换

hive中日期格式转换

日期时间格式大致分成时间戳和日期时间格式互转,字符串转化成日期时间格式,日期格式之间的转化

1.时间戳和日期互转

unix_timestamp函数,日期转时间戳

当函数参数为空时,返回当前时间戳。

当函数参数为空时,返回当前时间戳。
select unix_timestamp() --1706607208


不输入时间格式,默认’yyyy-MM-dd HH:mm:ss’格式

select unix_timestamp('2024-01-11 23:23:12') --1705015392
select unix_timestamp('2024-01-11')      ---返回null

正常情况下使用自定义格式,当输入类型和格式匹配返回正确值,否则返回null

select unix_timestamp('2024-01-11','yyyy-mm-dd') --1704931260



2.from_unixtime时间戳转日期

默认格式 ‘yyyy-MM-dd HH:mm:ss’,不能为空值,可以指定特定格式

select from_unixtime(1704931260) --2024-01-11 00:01:00
select from_unixtime(1704931260,'HH:mm:ss') --00:01:00



3.日期格式之间的互换


把20240111转化2024-01-11

select from_unixtime(unix_timestamp('20240111','yyyyMMdd'),'yyyy-MM-dd')


日期格式yyyy-MM-dd格式转化成其他格式
date_format主要针对yyyy-MM-dd的时间格式转化成其他格式的日期字符串。

select date_format('2024-01-11','yyyy/MM/dd')


4.其他时间函数,针对’yyyy-MM-dd HH:mm:ss’

1、to_date函数,返回日期时间中的日期部分
通常只能应用于’yyyy-MM-dd HH:mm:ss’格式的日期时间截取

select to_date('2024-01-11 12:10:21') --2024-01-11


2、year, month, day, hour, minute,second函数

select second('2024-01-11 12:10:21') ---21


3、日期转周函数weekofyear

select weekofyear('2024-01-11 10:03:01');--2



5.时间函数运算

1、datediff 日期比较函数,默认格式’yyyy-MM-dd HH:mm:ss’

select datediff('2024-01-11','2023-08-11')   --输出-153


2、时间增加函数 date_add

select date_add('2023-12-08',10) --2023-12-18

3、时间减少函数 date_sub

select date_sub('2023-09-11',10) --2023-09-01


4、获取两个时间的相差月份数

select floor(months_between('2023-07-01','2023-02-04')) --4


5.获取当前时间

select current_date()   --2024-01-30 获取日期格式
select unix_timestamp() --1706608131 获取时间戳

posted @ 2024-01-30 17:49  whiteY  阅读(4135)  评论(0)    收藏  举报