如何在每个Postgres版本中以char(8)格式获取服务器本地时间hh:mm:ss。
在9.1中它起作用:
select current_time::char(8)
返回适当的当地时间13:46:00
在9.5中它返回3小时的不同时间:
10点46分00秒
选择current_time,version()返回
"10:48:40.181735+00";"PostgreSQL 9.5.2, compiled by Visual C++ build 1800, 32-bit"
和
"13:48:51.775138+03";"PostgreSQL 9.1.2 on x86_64-unknown-linux-gnu, compiled by gcc-4.4.real (Debian 4.4.5-8) 4.4.5, 64-bit"
更新
两台服务器都使用默认的postgres.conf设置。 postgres.conf不包含时区设置。
在9.5 Windows 10中包含
#timezone = 'GMT'
#timezone_abbreviations = 'Default'
在9.1 Debian中包含
#timezone = '(defaults to server environment setting)'
#timezone_abbreviations = 'Default'
如果使用默认的postgresql.conf文件,如何在9.5中获取服务器本地时间?
看起来服务器不使用9.5中的操作系统设置
如何强制9.5从操作系统询问时区并在此区域返回时间?
答案 0 :(得分:2)
询问您想要的time zone
:
select current_time at time zone 'brt';
timezone
--------------------
08:26:16.778448-03
如果你需要一个字符串:
select to_char(current_timestamp at time zone 'brt', 'HH24:MI:SS');
to_char
----------
08:32:07
请注意to_char
函数不接受time
类型。请改用timestamp
。
从shell获取操作系统本地时区。在Linux中:
$ date +%Z
BRT
在psql中:
=> \! date +%Z
BRT
如果客户端有psql:
psql -c "\! date +%Z" --host localhost --dbname=cpn --no-password
BRT
有必要使用.pgpass
文件来避免提供密码。
答案 1 :(得分:0)
如果未在postgresql.conf中指定时区或作为服务器命令行选项,则服务器会尝试将TZ环境变量的值用作默认时区。如果未定义TZ或者不是PostgreSQL已知的任何时区名称,则服务器会通过检查C库函数localtime()的行为来尝试确定操作系统的默认时区。选择默认时区作为PostgreSQL已知时区中最接近的匹配。 (如果未指定,这些规则也用于选择log_timezone的默认值。)source
这意味着如果您没有定义时区,服务器会通过检查C库函数localtime()的行为来尝试确定操作系统的默认时区。
如果未在postgresql.conf中指定时区或作为服务器命令行选项,则服务器会尝试将TZ环境变量的值用作默认时区。
我认为您需要移除#
中的#timezone = 'GMT'
并将GMT
替换为'(defaults to server environment setting)'
由于'(defaults to server environment setting)'
未定义,因此服务器尝试通过检查C库函数localtime()的行为来确定操作系统的默认时区。
答案 2 :(得分:-2)
获取使用定义的时区计算的当地时间:
select current_time, version();
获取使用指定时区计算的当地时间:
select current_time at time zone 'US/Eastern';
获取定义的时区:
SELECT current_setting('TIMEZONE');
分配您要使用的时区:
set timezone='US/Eastern';
您可以看到不同的时区here