日期转换与时间戳转换
注释:时间戳是没有时区的概念的
1 spark
1.1时区设置
set spark.sql.session.timeZone=GMT+8;
set spark.sql.session.timeZone=UTC;
1.2时间戳格式化为日期
from_unixtime(floor(ts/1000),'yyyy-MM-dd')
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') ;
from_utc_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'),tz)
1.5动态指定时区转换
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
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')
|