想要在配置单元中将时间戳转换为日期格式
Want to convert timestamp to date format in hive
想要将此数字“20210412070422”转换为配置单元中的日期格式“2021-04-12”
我正在尝试,但是这个 returns 空值
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}).*','--')
如果您更喜欢使用 unix_timestamp/from_unixtime
select date(from_unixtime(unix_timestamp(ts, 'yyyyMMddHHmmss')))
from
(
select '20210412070422' as ts
)s
但它更复杂、更慢(涉及 SimpleDateFormat class)并且容易出错,因为如果数据不完全符合预期格式,例如“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。
想要将此数字“20210412070422”转换为配置单元中的日期格式“2021-04-12”
我正在尝试,但是这个 returns 空值
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}).*','--')
如果您更喜欢使用 unix_timestamp/from_unixtime
select date(from_unixtime(unix_timestamp(ts, 'yyyyMMddHHmmss')))
from
(
select '20210412070422' as ts
)s
但它更复杂、更慢(涉及 SimpleDateFormat class)并且容易出错,因为如果数据不完全符合预期格式,例如“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。