问题描述
我的年份和月份格式如下。年和月是列名
Year Month
2020 January
2019 October
并希望将它们转换为以下格式
01-01-2020
01-10-2019
我尝试过使用
cast(concat('01-',substring(month,1,3),'-',year) as timestamp) as Date_col
但无法使其工作。非常感谢帮助。谢谢!!
解决方法
在 SQL Server 中,您可以使用 DATEPART
和 FORMAT
来实现:
SELECT CONCAT('01-',FORMAT(DATEPART(MM,[Month] + ' 01 ' + [Year]),'0#'),'-',[Year]) AS Date_col
FROM yourTable
,
您正在尝试将 01-Jan-2019
转换为时间戳,但即使它有效,Hive 中的时间戳也不需要格式:dd-MM-yyyy
。时间戳具有以下格式:'yyyy-MM-dd HH:mm:ss.SSSSSSSSS'
(纳秒是可选的)。
unix_timestamp
函数以秒为单位将给定格式字符串转换为 unix 时间戳,from_unix_time
将 unix 时间戳转换为给定格式。
使用 from_unixtime(unix_timestamp(concat('01-',month,year),'dd-MMM-yyyy'),'dd-MM-yyyy')
将 'dd-MMM-yyyy'
转换为 'dd-MM-yyyy'
演示:
with
your_data as (
select stack(2,2020,'January',2019,'October'
) as ( Year,Month)
)
select Year,Month,from_unixtime(unix_timestamp(concat('01-','dd-MM-yyyy') as Date_col
from your_data
;
结果:
year month date_col
2020 January 01-01-2020
2019 October 01-10-2019
这也可以工作(不使用 01-
连接,使用“MMM-yyyy”格式):
from_unixtime(unix_timestamp(concat(month,'MMM-yyyy'),'dd-MM-yyyy')
如果要转换为真正的时间戳,请在不指定输出格式的情况下执行相同操作:
from_unixtime(unix_timestamp(concat(month,'MMM-yyyy')) --returns 2020-01-01 00:00:00
使用 SimpleDateFormat 类文档作为格式参考