impala日期格式常用转换

获取时间

//获取当前时间
select now(); //时间到毫秒,如:2022-07-21 13:57:14.435929000
select current_timestamp(); //与now()结果一样
select from_unixtime(unix_timestamp(),'yyyy-MM-dd') //如:2022-07-22
select to_date(now()) //如:2022-07-22
select from_unixtime(unix_timestamp()) //如:2022-07-22 09:59:34

时间格式转换

select  from_unixtime(unix_timestamp(),'yyyy/MM/dd HH:mm:ss')  //获取当前时间(格式为:年/月/日 时:分:秒)
select left (cast(now() as string),19)  //2022-07-22 10:01:38
select left (cast(now() as string),16)  //2022-07-22 10:01
select from_unixtime(unix_timestamp(a.字段名),'yyyy') as year,* from 表名 a //转换某个字段的时间格式

**时间戳提取**
select date_part('year', now()) //2022
select extract(now(), 'year')//2022
select extract(year from now())//2022
 select year('2022-07-27') //2022
 select month('2022-07-27') //7

时间转换为当年1月1日00点

select date_trunc('year',now()) //结果:2022-01-01 00:00:00
select date_trunc('year','2022-07-07 14:35:11') //2022-01-01 00:00:00
select date_trunc('year',a.字段名) as year,* from 表名  //2022-01-01 00:00:00

格式如下:

格式中文含义备注
microseconds微秒当前时间所在微秒
milliseconds毫秒当前时间所在毫秒
second当前时间所在秒
minute分钟当前时间所在分钟
hour小时当前时间所在小时
day当前时间所在天的第1天00点
week当前时间所在周的第1天00点
month当前时间所在月份第1天00点
year当前时间所在年份第1天00点
decade十年
century世纪
millennium一千年

时间差

//获取当前时间半年前的时间
 select add_months(from_unixtime(unix_timestamp(),'yyyy-MM-dd'),-6) //2022-01-28 00:00:00
//当前时间减30天
 select from_unixtime(unix_timestamp()-60*60*24*30) // 2022-06-28 15:49:55
//当前时间减1天
 select adddate(from_unixtime(unix_timestamp(),'yyyy-MM-dd HH:mm:ss'),-1) //2022-07-27 15:54:48

时间的加减

增加天数

 days_add(timestamp startdate,int days)
 如:
 select days_add('2022-07-25',1) //2022-07-26 00:00:00
 select days_add(from_unixtime(unix_timestamp()),2)//2022-07-31 10:17:19
 select days_add(now(),2)//2022-07-31 10:17:27.241333000

减少天数

 days_sub(timestamp startdate,int days)
 如:
 select days_sub(now(),2)  //2022-07-27 10:22:10.202118000
 select days_sub(from_unixtime(unix_timestamp()),2) //2022-07-27 10:21:35

格式如下:

格式中文含义
years_add增加年
years_sub减少年
months_add增加月
months_sub减少月
days_add增加天
days_sub减少天
weeks_add增加周
weeks_sub减少周
hours_add增加小时
hours_sub减少小时
minutes_add增加分钟
minutes_sub减少分钟
senconds_add增加秒
senconds_add减少秒

注:也可以用公共日期函数

date_add(timestamp startdate, interval_expression) 
date_sub(timestamp startdate, int days)
如:
 select date_add(from_unixtime(unix_timestamp()),2) //2022-07-31 10:57:06
 select date_sub(from_unixtime(unix_timestamp()),2) //2022-07-27 10:57:13

把时间转化成时间戳

select cast('1966-07-30' as timestamp); //1966-07-30 00:00:00
select cast('1985-09-25 17:45:30.005' as timestamp);
select cast('08:30:00' as timestamp);

把字符串转换成时间戳

cast('2019-10-14 18:00:41' as timestamp)
impala 没有好用的 timestamp_diff() 函数, 比如我们想要知道两个时间相差多少个小时, 不能直接求出, 下面是一个简单的步骤:
	1. 先算出一个小时对应的秒数是多少
	2. 将两个时间都转成秒数, 然后做差, 然后除以一个小时的秒数.
	3. unix_timestamp(finish_time)-unix_timestamp(start_time)可以得出之间的秒数
//计算两个时间间隔小时数
select ( unix_timestamp('2022-07-29 14:40:00')-unix_timestamp('2022-07-29 13:40:00'))/60/60 
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐