如何在Hive中将Unix Epoch时间转换为日期字符串

27

我有一个日志文件,其中包含时间戳列。时间戳使用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;
5个回答

59

哎呀,那看起来很丑。试试在Hive中使用这个函数:

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

或者如果时间戳是以 毫秒 而不是秒为单位:

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 ...

谢谢!节省了我很多时间。这正是我在寻找的! - Mahalakshmi Lakshminarayanan
4
请确保timestamp_value(这里是 unix_timestamp)以秒为单位,否则请使用from_unixtime(timestamp_value DIV 1000) - shriyog
我只能获取到秒的时间,但我也想要毫秒。我该怎么做? - Avinash Nishanth S
@BasilPaul 如我所述,您需要将时间戳值转换为秒,然后传递 - from_unixtime(timestamp_value DIV 1000) - shriyog
select FROM_UNIXTIME(cast(activation_date as bigint),'dd-MM-yyyy') from oct_pre_profile limit 5; 从 oct_pre_profile 表中选择前五个数据,将 activation_date 字段转换为大整数并使用 FROM_UNIXTIME 函数将其格式化为 'dd-MM-yyyy' 的日期格式。 - Jon Andrews
显示剩余4条评论

12

随着Hive和SparkSQL的最新版本发布,日期数据类型和类型转换选项已经可用。以下内容应该适用于Hive和Spark SQL。

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

11
如果您需要将日期转换为自定义格式,请使用以下内容:
select date_format(from_unixtime(epoch_datetime),'yyyyMM') as formatted_date from myHiveTable;


这将返回年月格式的日期,例如201708。


我认为您在格式说明符中可能漏掉了一个“y”。 - NYCeyes

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;

2
date_format 不是必需的,from_unixtime 可以接收另一个格式参数:select from_unixtime(epoch_datetime, 'yyyy-MM-dd') as day from table_name limit 20;https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF - Julian Qian
@JulianQian 没错,我使用了你更简洁的版本,它可以正常工作。 - NYCeyes

-1
select order_id, date_format(from_unixtime(order_date/1000),'yyy-MM-dd') as order_date ,order_customer_id,order_status
from orders

或者如果您在同一页面上看到任何错误,请尝试使用以下代码: select order_id, date_format(from_unixtime(order_date DIV 1000),'yyy-MM-dd') as order_date ,order_customer_id,order_status from orders


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