字符串到日期转换超时

时间:2015-04-28 20:27:29

标签: sql string postgresql casting timestamp

具有以下示例字符串:

'2015-01-01 23:51:00 AD'
'2015-01-01 24:51:00 AD'
'2015-01-01 26:51:00 AD'
'2015-01-01 27:51:00 AD'

有没有办法(通过运行SQL查询)来改变小时?如果高于24则执行hour - 24

结果行是:

'2015-01-01 23:51:00 AD'
'2015-01-01 00:51:00 AD'
'2015-01-01 02:51:00 AD'
'2015-01-01 03:51:00 AD'

1 个答案:

答案 0 :(得分:4)

It's not a date. It's a timestamp.

一种方式(很多):

SELECT overlay(string
               placing to_char(substring(string, 12, 2)::int % 24, '00')
               from 12 for 2);

然后你可以投了:(expression)::timestamp或使用to_timestamp()

String functions in the manual.
% is the modulo operator.

或者可能更快(丢弃时代指示器AD):

SELECT left(string, 10)::date + substring(string, 12, 8)::interval::time

interval允许任意数小时。当回到time时,你可以根据需要调整24小时。您只需添加datetime即可在Postgres中生成timestamp

SQL Fiddle.