【问题标题】:how to convert unix epoch time to date string in hive如何在 hive 中将 unix 纪元时间转换为日期字符串
【发布时间】:2011-08-26 22:40:42
【问题描述】:

我有一个包含时间戳列的日志文件。时间戳采用 unix 纪元时间格式。

我想根据带有分区年、月和日的时间戳创建一个分区。

到目前为止,我已经这样做了,但它抛出了一个错误。

PARSE ERROR cannot recognize input '(' in column type

这是我的代码。

from (
      from raw_data
            MAP  ${PREFIX}raw_data.line
            USING 's3://scripts/clean.py'
            AS (timestamp STRING, name STRING)
      ) map_out
INSERT OVERWRITE TABLE date_base_data_temp PARTITION(year(timestamp), month(timestamp)), day(timestamp))) 
    select map_out.name;

【问题讨论】:

    标签: function hive database-partitioning


    【解决方案1】:

    哎呀,看起来很难看。尝试在 Hive 中使用此功能:

    SELECT from_unixtime(unix_timestamp) as new_timestamp from raw_data ...
    

    或者如果时间戳是ms而不是秒:

    SELECT from_unixtime(unix_timestamp DIV 1000) as new_timestamp from raw_data ...
    

    将unix时间戳转换为YYYY-MM-DD HH:MM:SS格式,然后可以使用以下函数获取年月日:

    SELECT year(new_timestamp) as year, month(new_timestamp) as month, day(new_timestamp) as day ...
    

    【讨论】:

    • 谢谢!节省了我很多时间。这正是我想要的!
    • 确保timestamp_value(此处为unix_timestamp)以秒为单位,否则使用from_unixtime(timestamp_value DIV 1000)
    • 我只有时间到秒,但我也想要毫秒。我该怎么做?
    • @shriyog 我有纪元格式的日期。值为 1513708200000。请帮我查询将值转换为日期格式
    • @BasilPaul 正如我所提到的,您需要将时间戳值转换为秒然后通过 - from_unixtime(timestamp_value DIV 1000)
    【解决方案2】:

    随着 Hive 和 SparkSQL 的最新版本,日期和类型转换选项的数据类型可用。以下应该在 Hive 和 Spark SQL 中工作

    SELECT cast(from_unixtime(epoch_datetime) as date) from myHiveTable
    

    【讨论】:

      【解决方案3】:

      如果您需要将日期转换为自定义格式,请使用:

      select date_format(from_unixtime(epoch_datetime),'yyyyMM') as formatted_date from myHiveTable;
      


      它将日期返回为 yearMonth 例如201708

      【讨论】:

      • 我认为您可能在格式说明符中遗漏了一个y
      【解决方案4】:

      将此查询添加到需要将时间戳转换为字符串分区的日期字符串 yyyy-MM-dd 的列表中:

      hive> select date_format(from_unixtime(epoch_datetime), 'yyyy-MM-dd') as day from table_name limit 20;
      
      -- If required, remove the millis precision for timestamps
      hive> select date_format(from_unixtime(cast(epoch_datetime/1000 as bigint)), 'yyyy-MM-dd') as day from table_name limit 20;
      

      【讨论】:

      • date_format 不是必须的,from_unixtime 可以接收另一个格式参数:select from_unixtime(epoch_datetime, 'yyyy-MM-dd') as day from table_name limit 20; cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF
      • @JulianQian 你是对的。我用了你更简洁的版本,效果很好。
      【解决方案5】:
      select order_id, date_format(from_unixtime(order_date/1000),'yyy-MM-dd') as order_date ,order_customer_id,order_status
      from orders
      

      或者如果您看到任何错误,请尝试使用 选择 order_id, date_format(from_unixtime(order_date DIV 1000),'yyy-MM-dd') 作为 order_date ,order_customer_id,order_status 来自订单

      【讨论】:

        猜你喜欢
        • 2019-08-21
        • 2017-11-10
        • 2012-04-03
        • 2018-02-18
        • 2019-06-18
        • 2013-08-25
        • 2018-08-07
        • 1970-01-01
        • 2016-09-15
        相关资源
        最近更新 更多