How to convert Jan 1, 2021 12:40:46 PM time format to specified format by hive

During the development process, if you encounter something similar to Jan 1, 2021 12:40:46 PM, Jan 1, 2021 9:40:46 AM, you need to convert to the yyyy-MM-dd HH:mm:ss format, which is specially recorded.

Ideas:

  1. First convert the above format to a timestamp through the unix_timestamp function
  2. Then use from_unixtime to convert to the specified time format

Note: First of all, determine whether the suffix is ​​PM or AM. If it is AM, you can directly convert according to the above two steps. If it is PM and the hour is 12 o'clock, you can directly convert according to the above two steps. If it is not 12 o'clock, After converting to a timestamp, add 12*3600 (that is, add 12 hours), and then perform the second step of conversion.

select case when substr('Jan 1, 2021 12:40:46 PM', -2, 2) = 'PM' and from_unixtime(unix_timestamp('Jan 1, 2021 12:40:46 PM','MMMM dd, yyyy HH:mm:ss'),'HH') <> 12 then from_unixtime(unix_timestamp('Jan 1, 2021 12:40:46 PM','MMMM dd, yyyy HH:mm:ss')+43200,'yyyy-MM-dd HH:mm:ss')
       else from_unixtime(unix_timestamp('Jan 1, 2021 12:40:46 PM','MMMM dd, yyyy HH:mm:ss'),'yyyy-MM-dd HH:mm:ss') end as time;

select case when substr('Jan 1, 2021 1:40:46 PM', -2, 2) = 'PM' and from_unixtime(unix_timestamp('Jan 1, 2021 1:40:46 PM','MMMM dd, yyyy HH:mm:ss'),'HH') <> 12 then from_unixtime(unix_timestamp('Jan 1, 2021 1:40:46 PM','MMMM dd, yyyy HH:mm:ss')+43200,'yyyy-MM-dd HH:mm:ss')
       else from_unixtime(unix_timestamp('Jan 1, 2021 1:40:46 PM','MMMM dd, yyyy HH:mm:ss'),'yyyy-MM-dd HH:mm:ss') end as time;

select case when substr('Jan 1, 2021 1:40:46 AM', -2, 2) = 'PM' and from_unixtime(unix_timestamp('Jan 1, 2021 1:40:46 AM','MMMM dd, yyyy HH:mm:ss'),'HH') <> 12 then from_unixtime(unix_timestamp('Jan 1, 2021 1:40:46 AM','MMMM dd, yyyy HH:mm:ss')+43200,'yyyy-MM-dd HH:mm:ss')
       else from_unixtime(unix_timestamp('Jan 1, 2021 1:40:46 AM','MMMM dd, yyyy HH:mm:ss'),'yyyy-MM-dd HH:mm:ss') end as time;

operation result:

2021-01-01 12:40:46
2021-01-01 13:40:46
2021-01-01 01:40:46

Guess you like

Origin blog.csdn.net/lz6363/article/details/114556720