【问题标题】:Want to convert timestamp to date format in hive想要在配置单元中将时间戳转换为日期格式
【发布时间】:2021-09-29 17:58:46
【问题描述】:

想在 hive 中将此数字“20210412070422”转换为日期格式“2021-04-12”

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

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

【问题讨论】:

    标签: sql date hive timestamp hiveql


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 2015-08-19
      • 2020-02-23
      • 1970-01-01
      相关资源
      最近更新 更多