日期转换与时间戳转换(spark与persto的区别)

日期转换与时间戳转换

注释:时间戳是没有时区的概念的

1 spark

1.1时区设置
set spark.sql.session.timeZone=GMT+8; --设置为东八区时间
set spark.sql.session.timeZone=UTC; --设置为UTC时间
1.2时间戳格式化为日期
from_unixtime(floor(ts/1000),'yyyy-MM-dd')
--注释,使用此方法转换时间时,默认使用的是集群的时区(时区设置参考1.1)
--次函数的时间戳为10位的
1.3时间戳跨时区转换日期(集群时区与要转换的目的时区不一致问题)

假设集群默认时区UTC时区,要转化为东八区时间

方法一(需要指定时区):
1 在spark-sql中执行
set spark.sql.session.timeZone=GMT+8; --设置为东八区时间
2 select from_unixtime(floor(ts/1000),'yyyy-MM-dd') ...
获取一个时间戳

在这里插入图片描述

--在不指定时区的情况下,默认转换为集群时区时间(错误的结果)
select from_unixtime(1627354133,'yyyy-MM-dd HH:mm:ss')
--结果
from_unixtime(CAST(1627354133 AS BIGINT), yyyy-MM-dd HH:mm:ss)
2021-07-27 02:48:53
--设置东八区
set spark.sql.session.timeZone=UTC;
select from_unixtime(1627354133,'yyyy-MM-dd HH:mm:ss');

--结果
spark-sql> set spark.sql.session.timeZone=GMT+8;
key	value
spark.sql.session.timeZone	GMT+8

from_unixtime(CAST(1627354133 AS BIGINT), yyyy-MM-dd HH:mm:ss)
2021-07-27 10:48:53

方法二(不需要设置时区):
select from_utc_timestamp(from_unixtime(1627354133,'yyyy-MM-dd HH:mm:ss'),'GMT+8')
--结果
from_utc_timestamp(CAST(from_unixtime(CAST(1627354133 AS BIGINT), yyyy-MM-dd HH:mm:ss) AS TIMESTAMP), GMT+8)
2021-07-27 10:48:53

1.4日期格式转换
select from_unixtime(unix_timestamp('20210704','yyyymmdd'),'yyyy-mm-dd') ;--2021-07-04
--零时区转换任意时区的时间
from_utc_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'),tz) 
1.5动态指定时区转换
--tz为数据中的时区参数,在使用该方法是需要将集群时区指定为UTC
set spark.sql.session.timeZone=UTC;
select 
from_utc_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'),'GMT+8') as db
,from_utc_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'),tz) as biz,ts,tz
1.6转换月-天-小时
set spark.sql.session.timeZone=UTC;
select 
from_utc_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'),tz) as biz_time
,date_format(from_utc_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'),tz),'yyyy-MM') as biz_month
,date_format(from_utc_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'),tz),'yyyy-MM-dd') as biz_day
,date_format(from_utc_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'),tz),'HH') as biz_hour
,ts
,tz
from table_name 

在这里插入图片描述

2 presto-sql

1时间戳转换日期

format_datetime(from_unixtime(cast(ts as bigint)/1000,'GMT+8'),'yyyy-MM-dd')
format_datetime(from_unixtime(cast(ts as bigint)/1000,'GMT+8'),'yyyy-MM-dd')
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值