繁体   English   中英

SQL(HUE):有没有办法将 24 小时时间转换为 12 小时 AM / PM 格式与小时桶

[英]SQL (HUE) : Is there any way to convert 24 hrs time into 12 hrs AM / PM format with hours buckets

我有表A ,其中包含存储为时间戳数据类型的列时间

表 A:包含 24 小时格式的 HH:MM:SS 时间列。

Sample data below:

time
12:32:45
16:09:04
09:02:16
18:34:33
08:59:30

Now I want to create a bucket based on hours and adding AM/PM.

eg: 
time between 00:00:00 - 00:59:00 = 12 AM,
01:00:00 - 01:59:00 = 01 AM,
14:00:00 - 14:59:00 = 02 PM and so on.

Desired Output :

time     new_time
12:32:45  12 PM
16:09:04  04 PM
09:02:16  09 AM
18:34:33  06 PM
08:59:30  08 AM

请使用以下代码。 now()替换为查询的time

SELECT now(), lpad(CONCAT ( 
CAST (extract(hour from now()) + CASE WHEN extract(hour from now()) >12 THEN -12 
WHEN extract(hour from now())=0 THEN 12 
ELSE 0  END AS string) , 
CASE WHEN extract(hour from now())  >=12 THEN ' PM' ELSE ' AM' END),5,'0') as new_time 

解释 - 首先我检查小时是否> 12。 如果是,则减去 12 得到小时。
然后根据小时设置 AM/PM。
lpad 用于确保您获得 01 AM 格式的数据。 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM