PostgreSQL的时间/日期函数使用
PostgreSQL的时间/日期函数使用PostgreSQL的常用时间函数使用整理如下: 一、获取系统时间函数 1.1 获取当前完整时间 select now(); david=# select now(); now ------------------------------- 2013-0412 15:39:40.399711+08 (1 row) david=# current_timestamp 同 now() 函数等效。 select current_timestamp;
now
40:22.398709
1.2 获取当前日期 select current_date; select current_date;
date
----------
12
1.3 获取当前时间 select current_time; current_time;
timetz
------------------
43:31.101726=#
二、时间的计算 47:13.244721
2.1 两年后 select now() + interval '2 years';
?column?
201549:03.1688512 year;
?12.3787272 y;
??
----------------------------
25.469862 Y28.4108532Y31.122831
2.2 一个月后 1 month;
?0551:22.24373one month;
ERROR: invalid input syntax for type interval: "one month"
LINE 1: ;
^
david
2.3 三周前 - interval 3 week0322 16:00:04.203735
2.4 十分钟后 + 10 min;
?12:47.445744
说明: interval 可以不写,其值可以是:
2.5 计算两个时间差 使用age(timestamp,timestamp) select age(now(),timestamp 1989-02-05);
age
--------------------------------------
24 years 2 mons 7 days 17:05:49.119848
select age(2007-09-15);
age
----------------------
5 years 6 mons 27 days
(三、时间字段的截取
在开发过程中,经常要取日期的年,月,日,小时等值,PostgreSQL 提供一个非常便利的EXTRACT函数。 EXTRACT(field FROM source)
field 表示取的时间对象,source 表示取的日期来源,类型为 timestamp、time 或 interval。 3.1 取年份 select extract(year from now());
date_part
---------
2013
3.2 取月份 month now());
date_part
---------
4day from 2013-04-13);
date_part
---------
13SELECT EXTRACT(DAY FROM INTERVAL 40 days 1 minute40
3.3 查看今天是一年中的第几天 select extract(doy ---------
102
3.4 查看现在距1970-01-01 00:00:00 UTC 的秒数 select extract(epoch now());
date_part
----------------
1365755907.94474
3.5把epoch 值转换回时间戳 SELECT TIMESTAMP WITH TIME ZONE epoch' + 1369755555 * INTERVAL 1 second;
??
28 23:15
以上是基本的PG时间/日期函数使用,可满足一般的开发运维应用。 详细用法请参考: PostgreSQL官方说明:http://www.postgresql.org/docs/9.2/static/functions-datetime.html
分类:
Postgresql
标签:
postgresql,时间函数,日期函数
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |