Spark数据清洗【时间数据处理】
推荐
原创
©著作权归作者所有:来自51CTO博客作者大斌Coder的原创作品,请联系作者获取转载授权,否则将追究法律责任
(1) 时间类型 TIMESTAMP
-- timestamp
-- 年 月 日 时 分 秒 时区
-- 1. 获取当前时间 (年-月-日 时:分:秒.毫秒)
> SELECT current_timestamp();
2022-04-22 16:45:23.526
-- 2. 指定时刻毫秒级时间戳 --[转]--> 毫秒级时间 (年-月-日 时:分:秒.毫秒)
> select timestamp_millis(1650621284511);
2022-04-22 17:54:44.511
-- return timestamp
-- Since: 3.1.0
-- 3. 指定时间戳 --[转]--> 格式化时间 (年-月-日 时:分:秒)
> select from_unixtime(1650622091047/1000, 'yyyy-MM-dd HH:mm:ss');
2022-04-22 18:08:11
-- return string
> select from_unixtime(1650622091047/1000, 'yyyyMMdd');
20220422
(2) 日期类型 DTAE
-- date
-- 年-月-日
-- 1. 获取当前日期 (年-月-日)
> select current_date();
2022-04-22
-- 2. 日期格式化
> SELECT date_format(current_date(), 'yyyyMMdd');
20220422
-- return string
-- 3. 非标准化日期时间提取日期
> SELECT to_date('20161231 12:01:12', 'yyyyMMdd HH:mm:ss');
2016-12-31
-- return date
> SELECT to_date('2009-07-30 04:17:52');
2009-07-30
> SELECT to_date('2016-12-31', 'yyyy-MM-dd');
2016-12-31
(3) 时间戳 BIGINT
-- bigint
-- 秒级/毫秒级 时间戳 (13位/16位)
-- 1. 获取当前(年-月-日 时:分:秒)时间戳
> SELECT unix_timestamp();
1476884637
Since: 1.5.0
-- 2. 获取当前(年-月-日 时:分:秒.毫秒)时间戳
> SELECT unix_timestamp()*1000; -- 毫秒不精确
1476884637000
> select unix_millis(current_timestamp()); -- 毫秒精确
1650622091047 2022-04-22 18:08:11.047
-- return bigint
-- Since: 3.1.0
-- 3. 获取指定时间秒级时间戳
> SELECT unix_timestamp('2016-04-08', 'yyyy-MM-dd');
1460041200
-- 4.1 获取指定时间毫秒级时间戳
> select unix_millis(timestamp('2022-04-22 17:43:01.123'));
1650620581123
-- 4.2 获取指定时间毫秒级时间戳
date_format(to_timestamp(concat(from_unixtime(1559461463324/1000,'yyyy-MM-dd HH:mm:ss.'), 1559461463324%1000)),'yyyy-MM-dd HH:mm:ss.SSS') as c3
timestamp 和 to_timestamp 区别:
相同 : 都可以把日期转成时间类型 timestamp
不同 : to_timestamp可以格式化非标准日期成timestamp
to_timestamp('20220422', 'yyyyMMdd') -> 2022-04-22 00:00:00
timestamp('20220422') -> NULL
unix_timestamp 和 to_unix_timestamp 区别:
相同 : 都可以把日期转成时间戳类型 bigint
不同 : unix_timestamp()参数可为空
> select unix_timestamp(); -- 1650632081
> select from_unixtime(1650632081); -- 2022-04-22 20:54:41