Postgresql 日期和时间类型

本文介绍了PostgreSQL中处理时间与日期的方法,包括不同格式的输入、时区的使用及如何设置日期样式。同时,还详细讲解了PostgreSQL提供的各种日期时间函数,如current_date、current_time等,并对比了它们在事务中的行为差异。

 作者:瀚高PG实验室 (Highgo PG Lab)- 天蝎座

timestamp with[out] time zone    日期时间(时区)  
time with[out] time zone   		 只用于一日内的时间(时区)    

可以精确到毫秒。MySQL只能到秒。
默认都不会显示时区,需要显示的指定with time zone。

highgo=# select time '120900';
   time   
----------
 12:09:00
(1 row)

highgo=# select time '120900 PST';
   time   
----------
 12:09:00
(1 row)

highgo=# select time WITH time zone '120900 PST';
   timetz    
-------------
 12:09:00-08
(1 row)



在输入日期时,有很多种格式。有时候需要确定datestyle。

highgo=# create table t(date date);
CREATE TABLE
highgo=# insert into t values (date '12-18-2010');
INSERT 0 1
highgo=# select * from t;
    date    
------------
 2010-12-18
(1 row)

highgo=# show datestyle;
 DateStyle 
-----------
 ISO, MDY
(1 row)

highgo=# set datestyle = 'YMD';
SET

highgo=# insert into t values (date '2010-12-19');
INSERT 0 1
highgo=# select * from t;
    date    
------------
 2010-12-18
 2010-12-19
(2 rows)


注: 建议使用 2017-12-18 这种方式输入日期。任何方式下都是2017年12月18日。

PostgreSQL 提供可许多返回当前日期和时间的函数。
部分函数按照当前事务的开始时刻返回结果:
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURRENT_TIME(precision)
LOCALTIME
LOCALTIMESTAMP
now()
transaction_timestamp()  感觉这个描述更符合实际情况

另外部分函数返回实时时间值,在事务中也会随时间变化。
statement_timestamp()
clock_timestamp()
timeofday()              返回的是text字符串


在同一个事务中,和now()同类型的函数不会变化,和statement_timestamp()同类型的函数则相反。

highgo=# begin;
BEGIN
highgo=# select now();
              now              
-------------------------------
 2017-12-18 12:18:32.263891+08
(1 row)

highgo=# select now();
              now              
-------------------------------
 2017-12-18 12:18:32.263891+08
(1 row)

highgo=# select statement_timestamp();
      statement_timestamp      
-------------------------------
 2017-12-18 12:19:15.463267+08
(1 row)

highgo=# select statement_timestamp();
      statement_timestamp      
-------------------------------
 2017-12-18 12:19:18.975693+08
(1 row)

highgo=# commit;
COMMIT


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值