如何在Hive中提取MMM格式(如Jan)的月份?执行脚本报错求助
Hive提取MMM格式月份报错的解决办法
报错原因
你遇到的date_format() unknown错误,核心原因是你的Hive版本低于1.2.0——date_format是Hive 1.2.0才新增的函数,低版本环境根本没有这个函数。
替代方案
不用date_format,直接用低版本Hive支持的from_unixtime函数就能实现需求,因为它本身支持指定输出格式:
情况1:start_date是时间戳类型
直接在from_unixtime后加格式参数'MMM':
select from_unixtime(start_date, 'MMM') as month from table1;
情况2:start_date是字符串类型的日期(比如yyyy-MM-dd格式)
先把字符串转成时间戳,再指定格式:
select from_unixtime(unix_timestamp(start_date, 'yyyy-MM-dd'), 'MMM') as month from table1;
注意:月份缩写的语言问题
如果执行后返回的是中文月份(比如“一月”),需要先设置会话参数切换到英文环境:
-- 临时设置英文语言环境 set system:user.language=en; set system:user.country=US; -- 再执行查询 select from_unixtime(start_date, 'MMM') as month from table1;
测试验证
可以先拿一个已知时间戳测试,确认效果:
select from_unixtime(1609459200, 'MMM'); -- 对应2021-01-01,应该返回Jan
内容的提问来源于stack exchange,提问作者user15676
相关产品推荐
相关产品推荐

