如何在Hive中将时间戳转换为日期格式

4
想要将数字 '20210412070422' 转换为日期格式 '2021-04-12' 在hive中。
我正在尝试,但这会返回空值。
使用以下代码可以将数字转换为日期格式:
from_unixtime(unix_timestamp('20210412070422', 'yyyyMMddHHmmss'))
请注意,如果您要将一个变量转换为日期格式,请使用变量名而不是数字。
1个回答

2

最好的方法是尽可能避免使用unix_timestamp/from_unixtime,而在您的情况下这是可能的。date()可以被移除,yyyy-MM-dd格式的字符串与date类型兼容:

select date(concat_ws('-',substr(ts,1,4),substr(ts,5,2),substr(ts,7,2)))
from
(
select '20210412070422' as ts
)s

结果:

2021-04-12

使用regexp_replace的另一种高效方法:

select regexp_replace(ts,'^(\\d{4})(\\d{2})(\\d{2}).*','$1-$2-$3')

如果您更喜欢使用unix_timestamp/from_unixtime

select date(from_unixtime(unix_timestamp(ts, 'yyyyMMddHHmmss')))
from
(
select '20210412070422' as ts
)s

但是这种方法更加复杂,速度较慢(涉及SimpleDateFormat类),且容易出错,因为如果数据不完全符合预期格式,例如 '202104120700',则无法正常工作。

当然,您可以通过截取所需长度的子字符串并使用yyyyMMdd模板来使其更加可靠:

select date(from_unixtime(unix_timestamp(substr(ts,1,8), 'yyyyMMdd')))
from
(
select '20210412070422' as ts
)s

这让它变得更加复杂。

只有在像“2021Apr12blabla”这样的数据格式无法使用简单的substr或regexp_replace时,才使用unix_timestamp/from_unixtime。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接