gpt4 book ai didi

sql - 想要在配置单元中将时间戳转换为日期格式

转载 作者:行者123 更新时间:2023-12-05 05:58:26 25 4
gpt4 key购买 nike

想要将这个数字 '20210412070422' 转换为 hive 中的日期格式 '2021-04-12'

我正在尝试,但这会返回空值

from_unixtime(unix_timestamp(eap_as_of_dt, 'MM/dd/yyyy'))

最佳答案

最好的方法 是尽可能不使用 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

这使它变得更加复杂。

仅当简单的 substr 或 regexp_replace 不适用于“2021Apr12blabla”等数据格式时,才使用 unix_timestamp/from_unixtime。

关于sql - 想要在配置单元中将时间戳转换为日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68485082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com