根据时间戳记值创建一个新列

时间:2018-08-01 19:04:38

标签: sql postgresql

我的表中有一个24小时格式的“ local_time”列。我想根据时间戳创建一个值为AM,PM的新列。

示例

     Local_time 

2018-06-29 10:57:59
2018-06-29 12:17:42
2018-07-02 15:46:09

预期

 Local_time                    day_time

2018-06-29 10:57:59               AM
2018-06-29 12:17:42               PM
2018-07-02 15:46:09               PM

3 个答案:

答案 0 :(得分:2)

使用case when并与时间进行比较

select Local_time,
case when EXTRACT(HOUR FROM Local_time)<12 then 'AM' else 'PM' end as day_time 
from your_table   

答案 1 :(得分:1)

只需使用PMAM进行to_char转换:

create table tab( local_time timestamp );
insert into tab values(now());
insert into tab values(('2018-06-29 10:57:59')::timestamp);

SELECT local_time, 
       to_char(local_time,'AM') day_time1,
       to_char(local_time,'PM') day_time2
  FROM tab;

local_time                  day_time1   day_time2
2018-08-01T22:17:52.599662Z    PM          PM
2018-06-29T10:57:59Z           AM          AM

SQL Fiddle Demo

答案 2 :(得分:0)

您可以尝试使用extract来获取hour号,然后使用CASE WHEN

SELECT local_time, 
     (CASE WHEN extract(hour from local_time) < 12 THEN 'AM' ELSE 'PM' END) day_time
FROM t

sqlfiddle

[结果]

|           local_time | day_time |
|----------------------|----------|
| 2018-06-29T10:57:59Z |       AM |
| 2018-06-29T12:17:42Z |       PM |
| 2018-07-02T15:46:09Z |       PM |