cc *_*ung 10 sql postgresql timestamp
在Postgres中,是否可以更改时间戳的默认格式掩码?
现在回来了
2012-01-03 20:27:53.611489
Run Code Online (Sandbox Code Playgroud)
我想像这样决定分钟:
2012-01-03 20:27
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过接收应用程序在单个列上执行此操作,to_char() as
或者使用substr()
接收应用程序将其删除,但最初正确格式化将节省大量工作并减少大量错误.
Eri*_*ski 13
在PostgreSQL中,时间戳的格式与存储无关.一个答案是使用to_char
时间戳并将其格式化为您需要的任何格式,如下所示:
select to_char(current_timestamp, 'yyyy-MM-dd HH24:MI:SS.MS');
select to_timestamp('2012-10-11 12:13:14.123',
'yyyy-MM-dd HH24:MI:SS.MS')::timestamp;
Run Code Online (Sandbox Code Playgroud)
但是如果必须设置默认格式:
全局更改postgresql时间戳格式:
看看你的时区,将其作为sql查询运行:
show timezone
Result: "US/Eastern"
Run Code Online (Sandbox Code Playgroud)
因此,当您打印出current_timestamp时,您会看到:
select current_timestamp
Result: 2012-10-23 20:58:35.422282-04
Run Code Online (Sandbox Code Playgroud)
将-04
在年底为您的时间相对于UTC区.您可以通过以下方式更改时区:
set timezone = 'US/Pacific'
Run Code Online (Sandbox Code Playgroud)
然后:
select current_timestamp
Result: 2012-10-23 18:00:38.773296-07
Run Code Online (Sandbox Code Playgroud)
请注意-07
那里,这意味着我们太平洋距离UTC有7个小时的路程.如何让难看的时区消失?一种方法是制作一个表,它默认为没有时区的时间戳:
CREATE TABLE worse_than_fail_table
(
mykey INT unique not null,
fail_date TIMESTAMP not null
);
Run Code Online (Sandbox Code Playgroud)
然后,如果您向该表添加时间戳并从中进行选择
select fail_date from worse_than_fail_table
Result: 2012-10-23 21:09:39.335146
Run Code Online (Sandbox Code Playgroud)
是的,最后没有时区.但是你想要更好地控制时间戳默认显示的方式!你可以这样做:
CREATE TABLE moo (
key int PRIMARY KEY,
boo text NOT NULL DEFAULT TO_CHAR(CURRENT_TIMESTAMP,'YYYYMM')
);
Run Code Online (Sandbox Code Playgroud)
它是一个文本字段,可让您在执行操作时更好地控制默认情况下的显示方式select somecolumns from sometable
.请注意,您可以将字符串转换为时间戳:
select '2012-10-11 12:13:14.56789'::timestamp
Result: 2012-10-11 12:13:14.56789
Run Code Online (Sandbox Code Playgroud)
您可以转换current_timestamp以timestamp
删除时区:
select current_timestamp::timestamp
Result: 2012-10-23 21:18:05.107047
Run Code Online (Sandbox Code Playgroud)
你可以像这样摆脱时区:
select current_timestamp at time zone 'UTC'
Result: "2012-10-24 01:40:10.543251"
Run Code Online (Sandbox Code Playgroud)
但如果你真的想要时区,你可以这样做:
select current_timestamp::timestamp with time zone
Result: 2012-10-23 21:20:21.256478-04
Run Code Online (Sandbox Code Playgroud)
你可以用提取物抽出你想要的东西:
SELECT EXTRACT(HOUR FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 20
Run Code Online (Sandbox Code Playgroud)
这个怪物:
SELECT TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-05' AT TIME ZONE 'EST';
Result: 2001-02-16 20:38:40
Run Code Online (Sandbox Code Playgroud)
to_char()
用于创建字符串文字。如果要使用其他时间戳记值,请使用:
date_trunc('minute', now())
Run Code Online (Sandbox Code Playgroud)
对于输入掩码,可以使用:
to_timestamp('2012-01-03 20:27:53.611489', 'YYYY-MM-DD HH24:MI')
Run Code Online (Sandbox Code Playgroud)
timestamp without time zone
通过附加到进行强制转换::timestamp
。
据我所知,PostgreSQL中没有设置默认情况下会从时间戳文字中减去秒数。