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