【presto & hive 对比1】presto 与 hive的时间转换对比

工作中经常遇到的问题

  1. log_date:20200110 需要转换为标准日期,或者与时间戳数据进行比较
  2. 工作环境涉及到presto与hive, 利用presto检查查询时速度更快,因此一般需要同时用presto和hive的语法对日期进行转换

因此本篇博文主要对最近用到的时间转换进行梳理

问题1:时间格式转换

例子: 当前时间20200110 转化为2020-01-10

--输出 2020-01-10
--hive
select to_date(from_unixtime(UNIX_TIMESTAMP('20200110','yyyyMMdd')));

--presto
select (format_datetime(date_parse('20200110','%Y%m%d'),'yyyy-MM-dd') ;

hive string与各种格式时间的转换: http://www.mamicode.com/info-detail-2587004.html

问题2: 时间的加减

例子: 原时间为20200110 需先转化为标准日期形式再加减

--hive 
select date_add('2020-01-12',10);
select date_add(to_date(from_unixtime(UNIX_TIMESTAMP('20200110','yyyyMMdd'))),10);

--presto
select date_add('day',-6,cast('2020-07-07' as date)); --第三个参数不转换为date格式, 会报错 第三个参数必须为date格式
select 
date_add('day', -6, cast(format_datetime(date_parse('20200110','%Y%m%d'),'yyyy-MM-dd') as date));

hive中date_add, date_sub, date_diff的用法: https://www.cnblogs.com/yfb918/p/10813856.html
date_sub与date_add用法几乎一样

问题3: 时间戳转日期

--hive
select from_unixtime(1578585600);
--加格式
select from_unixtime(1578585600,'yyyyMMdd');

--presto
select from_unixtime(1578585600);
--加格式
select format_datetime(from_unixtime(1578585600),'yyyy-MM-dd');

问题4: 日期转时间戳

--hive 
select unix_timestamp('20200110' ,'yyyyMMdd'); --10位时间戳

-- presto 
select to_unixtime(cast('2020-01-10' as date));
select to_unixtime(cast(format_datetime(date_parse('20200110','%Y%m%d'),'yyyy-MM-dd') as date));

问题5: 计算两个日期之间的diff

--hive
select datediff('2017-09-15','2017-09-01');-- 结果14

--presto 
select date_diff('day',cast('2018-09-05' as date),cast('2018-09-07' as date));

-- 1)需要提供参数'day',表示要查询的是天数间隔;要查询小时,则提供参数'hour'
-- 2)并且后面传参限制为date类型;
-- 3)最后要注意是后面减去前面 --与hive不同

问题6: 当前时间

--hive
select current_date;
select unix_timestamp(); --获取当前时间戳
select from_unixtime(unix_timestamp());

-- presto
select now();  --精确到今天的时分秒
select current_date; --精确到今天的年月日
select current_date - interval '1' day; 精确到昨天的年月日
--hive其它日期查询
select current_timestamp; --查询当前系统时间(包括毫秒数);  
select dayofmonth(current_date); -- 查询当月第几天
select last_day(current_date); --月末
select date_sub(current_date,dayofmonth(current_date)-1); --当月第1天: 
select add_months(date_sub(current_date,dayofmonth(current_date)-1),1); --下个月第1天

presto time官网介绍:https://prestodb.io/docs/current/functions/datetime.html
其它参考: https://blog.csdn.net/qq646748739/article/details/77997276

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值