环境
系统平台:Microsoft Windows (64-bit) 10
版本:5.6.4
文档用途
postgresql日期/时间数据类型中有无时区的学习使用,时间戳的认识和使用。
详细信息
本文演示日期/时间数据类型的有无时区的差异使用,时间戳的认识和使用。
名字 存储尺寸 描述 最小值 最大值 解析度
timestamp [ (p) ] [ without time zone ] 8字节 包括日期和时间(无时区) 4713 BC 294276 AD 1微秒 / 14位
timestamp [ (p) ] with time zone 8字节 包括日期和时间,有时区 4713 BC 294276 AD 1微秒 / 14位
date 4字节 日期(没有一天中的时间) 4713 BC 5874897 AD 1日
time [ (p) ] [ without time zone ] 8字节 一天中的时间(无日期) 00:00:00 24:00:00 1微秒 / 14位
time [ (p) ] with time zone 12字节 一天中的时间(不带日期),带有时区 00:00:00+1459 24:00:00-1459 1微秒 / 14位
interval [ fields ] [ (p) ] 16字节 时间间隔 -178000000年 178000000年 1微秒 / 14位
注意:SQL要求只写timestamp等效于timestamp without time zone,并且PostgreSQL鼓励这种行为。timestamptz被接受为timestamp with time zone的一种简写,这是一种PostgreSQL的扩展。
1,日期数据类型中的有无时区的格式
有时区:
highgo=# select now()::timestamptz;
now
-------------------------------
2020-01-14 15:17:29.906248+08
(1 行记录)
无时区:
highgo=# select now()::timestamp;
now
----------------------------
2020-01-14 15:18:22.210588
(1 行记录)
给日期设置精度:
highgo=# select now()::timestamp(1);
now
-----------------------
2020-01-14 15:19:41.4
(1 行记录)
highgo=# select now()::timestamptz(1);
now
--------------------------
2020-01-14 15:20:52.3+08
(1 行记录)
2,时间数据类型中的有无时区格式
无时区:
highgo=# select now()::time without time zone;
now
-----------------
15:25:19.426667
(1 行记录)
highgo=# select now()::time;
now
-----------------
15:24:59.619024
(1 行记录)
注意:只写time等效于time without time zone。
有时区:
highgo=# select now()::time with time zone;
now
--------------------
15:26:56.803518+08
(1 行记录)
创建表定义日期/时间类型:
highgo=# create table test5(data1 timestamp,data2 timestamptz,time1 time,time2 time with time zone);
CREATE TABLE
highgo=# insert into test5 values(now(),now(),now(),now());
INSERT 0 1
highgo=# select * from test5;
data1 |data2 | time1 | time2
---------------------------+------------------------------+----------------+-------------------
2020-01-14 15:31:59.98203 | 2020-01-14 15:31:59.98203+08 | 15:31:59.98203 | 15:31:59.98203+08
(1 行记录)
二,时间戳的使用
SQL标准通过“+”或者“-”符号的存在以及时间后面的时区偏移来区分timestamp without time zone和timestamp with time zone文字。因此,根据标准,
TIMESTAMP ‘2020-01-14 15:37:41’
是一个timestamp without time zone, 而
TIMESTAMP ‘2020-01-14 15:37:41.363814+08’
是一个timestamp with time zone。PostgreSQL从来不会在确定文字串的类型之前检查其内容,因此会把上面两个都看做是 timestamp without time zone。因此要保证把上面的文字当作timestamp with time zone看待, 就要给它正确的显式类型:
TIMESTAMP WITH TIME ZONE ‘2020-01-14 15:37:41.363814+08’
如果一个文字已被确定是timestamp without time zone,PostgreSQL将不声不响忽略任何其中指出的时区。 即,结果值是从输入值的日期/时间域衍生出来的,并且没有就时区进行调整。
1421

被折叠的 条评论
为什么被折叠?



