注释:时间戳是没有时区的概念的
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:531.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,tz2 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')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)