PostgreSQL数据类型支持6种时间数据类型。以下图所示:html
time、timestamp和interval接受可选精度值 p,精度值是秒域中小数点后保留位数。缺省状况下,精度没有明确限制,timestamp和interval类型p容许范围从 0 到 6。sql
timestamp默认以8字节整数储存,整个数值范围内保持微秒以上精度,当被修改成双精度浮点数时,极端状况下,精度会降低到毫秒级以上。数据库
interval类型附加选项fields经过下列短语限制存储fields集合:post
YEAR MONTH DAY HOUR MINUTE SECOND YEAR TO MONTH DAY TO HOUR DAY TO MINUTE DAY TO SECOND HOUR TO MINUTE HOUR TO SECOND MINUTE TO SECOND
注意若是fields和p被指定,fields必须包括SECOND,由于精度只应用于秒。postgresql
类型time with time zone是SQL标准,但可能影响可用性。大多数状况下, date、time、timestamp without time zone和timestamp with time zone组合就能提供任何应用所需全范围日期/时间功能。code
时间输入格式为htm
type[ fields ] [ ( 精度 ) ] [ | with time zone] 'timevalue'
以下代码演示插入时间或日期。get
test=# create table testdatetime(id int,testdate date,testtime time); CREATE TABLE test=# insert into testdatetime values(1,'1644-1-1','01:11:11'),(2,'2017-11-9','15:02:22+08'); INSERT 0 2 test=#
还能够查看数据库系统时间显示格式。例如YMD为年月日格式。it
---查看DateStyle test=# show datestyle; DateStyle ----------- ISO, YMD (1 行记录) ---修改DateStyle test=# set DateStyle='YMD'; SET test=#
插入数值必须符合设定日期格式,不然可能会致使出错或输入错误。table
test=# insert into testdatetime values(1,'1795/1/3','01:11:11'); INSERT 0 1 test=# insert into testdatetime values(1,'1979 June 1','01:11:11'); INSERT 0 1 test=# insert into testdatetime values(1,'1979 June 1','01:11:11');
如上代码可知,不一样DateStyle可能会输出结果不相同,或者提示错误。
推荐"-"做为分隔符,推荐年月日方式输入日期数值。"/"可能会致使歧义。也能够使用"2017-July-1"相似明确无歧义格式输入日期和时间。
---输入公元前时间、儒略历日期 ---AD 放在最后 test=# insert into testdatetime values(3,'117-1-9 BC','16:00:00'),(5,'J2455000','10:17:20'); INSERT 0 3 test=#
查询已输入数据结果。
test=# select * from testdatetime; id | testdate | testtime ----+---------------+---------- 1 | 1644-01-01 | 01:11:11 2 | 2017-11-09 | 15:02:22 1 | 1795-01-03 | 01:11:11 1 | 1979-06-01 | 01:11:11 1 | 1979-06-01 | 01:11:11 3 | 0117-01-09 BC | 16:00:00 5 | 2009-06-17 | 10:17:20 (7 行记录) test=#
time数据类型等效于time without time zone。当输入带市区格式时,时区信息自动被剔除。
test=# insert into testdatetime values(4,'1979 June 1','01:11:11+8'); test=# select * from testdatetime where id =4; id | testdate | testtime ----+------------+---------- 4 | 1979-06-01 | 01:11:11 (1 行记录) test=# ---不推荐,无时分秒分隔符,分隔符推荐: test=# insert into testdatetime values(4,'1979 June 1','011111+8'); INSERT 0 1 test=#
输入有时区时间数据使用有时区数据类型。
test=# create table testdatetimewithtimezone(id int,timewithzone time with time zone); CREATE TABLE ---插入不一样类型带时区时间数据 test=# insert into testdatetimewithtimezone values(1,'09:17:22.011111'),(2,'17:33:59+11'),(3,'231545+07:45'); INSERT 0 3 test=#
推荐例如"07:59:59.111111+08:00"格式输入数据,时区缩写和声明时区等格式可能致使输入错误发生。
test=# select * from testdatetimewithtimezone; id | timewithzone ----+-------------------- 1 | 09:17:22.011111+08 2 | 17:33:59+11 3 | 23:15:45+07:45 (3 行记录) test=#
参考连接:
https://www.postgresql.org/docs/current/static/datatype-datetime.html