我已经尽可能一个人了。
我需要替换postgres中日期时间戳内的时间。
这是:
2015-11-20 08:00:00
需要这样做:
2015-11-20 09:00
但是一年中的每一天(只有时间变化)
这就是我到目前为止所拥有的。(我近在咫尺吗?)
UPDATE
events
SET
starttime = regexp_replace(starttime,
E’[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-0]{1}[8-8]{1}:[0-0]{1,2}:[0-0]{1,2}’,
E’[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-0]{1}[9-9]{1}:[0-0]{1,2}:[0-0]{1,2}’,‘g’)
WHERE
account_id = 9
AND starttime ~ E’[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-0]{1}[8-8]{1}:[0-0]{1,2}:[0-0]{1,2}’;
发布于 2015-03-04 11:48:25
我希望您的starttime
列是timestamp
或timestamp with time zone
,但是如果我怀疑它不是,它可能需要转换。
UPDATE events SET
starttime = starttime::timestamp + '1 hour'::interval
WHERE account_id = 9 AND extract(hour from starttime::timestamp) = 8;
与Remi的回答一样,有关日期时间函数的更多信息,请参考手册。
发布于 2015-03-04 11:22:40
这些文档对于这个主题非常有用。
在以下搜索框中键入add 1 hour timestamp
:
http://www.postgresql.org/docs/9.4/interactive/index.html
在第一次点击时生成以下页面:
http://www.postgresql.org/docs/9.4/static/functions-datetime.html
所以你可以做这样的事
timestamp '2001-09-28 01:00' + interval '1 hour'
另外,如果您的源是一个列(即mydatecolumn),它可能变成:
mydatecolumn::timestamp + interval '1 hour'
发布于 2015-03-04 12:06:10
我不太清楚您想要做什么,但是如果您想要做的唯一一件事是向starttime
时间戳添加一个小时,不要将regexp用于日期/时间操作。别这样就行。
加一个小时
Regexps用于操作文本数据,但时间戳是一个TIMESTAMP
--它的内部结构更加复杂,允许精确操作,而它的文本表示只是原始数据的“打印”版本。同样- TIMESTAMP
是postgresql数据类型,所以直接操作它,而不是通过使用regexp的“打印”文本形式。
更确切地说,您应该这样做:
UPDATE
events
SET
starttime = starttime + interval '1 hour'
WHERE
account_id = 9
但是,如果我没有得到它,并且您只想更改08:00
时间(正如您的格式错误的update语句所建议的那样),则可以使用EXTRACT(field FROM source)
。
UPDATE
events
SET
starttime = starttime + interval '1 hour'
WHERE
account_id = 9 AND EXTRACT(hour FROM starttime) = 8
(并类似于分钟或秒等)
无效正则表达式
即使使用regexp操作TIMEDATE
不是很明智,您的regexp表达式在几个方面也是错误的:
regexp_replace
调用中有两个regexp,它的形式为regexp_replace(string, regexp, replacement)
。但是,即使在替换时也使用regexp字符串,这样做的目的是:
选择regexp_replace('2015-11-20 08:00:00“,E'0-9{4}-0-9{1,2}-0-9{1,2} -0-0{1,2}8{1}:0-0{1,2}:0-0{1,2}:0-0{1,2}-9{1,2}-9{1,2}-9{1,2}:0-0,2}:0-{1,2}:0-{1,2}‘,'g');0-9{4}-0-9{1,2}-0-9{1,2} 0{1}9-9{1}:0-0{1,2}:0-0{1,2}
因此,您可以看到,您刚刚用replacement
字符串替换了所有内容。Bettew replacement
字符串将引用由regexp
匹配的组,这就引出了第二个问题:replacement
字符串中添加对这些组的引用,您将得到:
选择regexp_replace('2015-11-20 08:00:00',E‘(0-9{1,2})-(0-9{1,2})-(0-9{1,2})(0-0{1,2})(8-8{1}):(0-0{1,2}):(0-0{1,2})’,E‘1-2-\3 \4\5:\6:\7',’g‘;regexp_replace
看上去差不多不错。但是,既然您想要替换08:00
,那么让我们将其更改为:
选择regexp_replace('2015-11-20 08:00:00',E‘(0-9{1,2})-(0-9{1,2})-(0-9{1,2})(0-0{1,2})(8-8{1}):(0-0{1,2}):(0-0{1,2})’,E‘1-2-3 09:00:00,’g‘;regexp_replace[0-0]{1}
来匹配零(或其他单个字符)是不必要的,普通的0
就足够了,所以我只是准确地添加了08:00:00
字符串。(您可以将其更改为[01][0-9]:00:00
以匹配每小时一次,也可以将[0-9]{2}:[0-9]{2}:[0-9]{2}
更改为随时匹配)
选择regexp_replace('2015-11-20 08:00:00',E'(0-9{4})-(0-9{1,2})-(0-9{1,2}) 08:00‘,E’1-\2-\3 09:00:00‘;regexp_replacehttps://stackoverflow.com/questions/28853098
复制相似问题