PostgreSQL的时间/日期函数使用

前端之家收集整理的这篇文章主要介绍了PostgreSQL的时间/日期函数使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

http://www.cnblogs.com/mchina/archive/2013/04/15/3010418.html@H_502_1@

Postgresql的常用时间函数使用整理如下:@H_502_1@

一、获取系统时间函数@H_502_1@

1.1 获取当前完整时间@H_502_1@

select now();@H_502_1@

@H_502_26@
  1. david=# select now();
  2. now
  3. -------------------------------
  4. 2013-0412 15:39:40.399711+08
  5. (1 row)
  6. david=#
@H_502_26@ @H_502_26@

current_timestamp 同 now() 函数等效。@H_502_1@

select current_timestamp; now 40:22.398709 1.2 获取当前日期@H_502_1@

select current_date;@H_502_1@

select current_date; date ---------- 12 ( 1.3 获取当前时间@H_502_1@

select current_time;@H_502_1@

current_time; timetz ------------------ 43:31.101726=#
@H_502_26@ @H_502_26@

二、时间的计算@H_502_1@

47:13.244721 2.1 两年后@H_502_1@
select now() + interval '2 years'; ?column? 201549:03.1688512 year'; ?12.3787272 y'; ?column? ---------------------------- 25.469862 Y28.4108532Y31.122831 2.2 一个月后@H_502_1@
1 month'; ?0551:22.24373one month'; ERROR: invalid input Syntax for type interval: "one month" LINE 1: '; ^ david 2.3 三周前@H_502_1@
- interval 3 week0322 16:00:04.203735 2.4 十分钟后@H_502_1@
+ 10 min'; ?12:47.445744 说明:@H_502_1@

interval 可以不写,其值可以是:@H_502_1@

Abbreviation Meaning
Y Years
M Months (in the date part)
W Weeks
D Days
H Hours
M Minutes (in the time part)
S Seconds

@H_502_1@



@H_502_1@

2.5 计算两个时间差@H_502_1@

使用age(timestamp,timestamp)@H_502_1@

select age(now(),timestamp 1989-02-05'); age -------------------------------------- 24 years 2 mons 7 days 17:05:49.119848 (=#
@H_502_26@ @H_502_26@
select age(2007-09-15'); age ---------------------- 5 years 6 mons 27 days (三、时间字段的截取@H_502_1@

在开发过程中,经常要取日期的年,月,日,小时等值,Postgresql 提供一个非常便利的EXTRACT函数@H_502_1@

  1. EXTRACT(field FROM source)
@H_502_26@

field 表示取的时间对象,source 表示取的日期来源,类型为 timestamp、time 或 interval。@H_502_1@

3.1 取年份@H_502_1@

select extract(year from now()); date_part --------- 2013 ( 3.2 取月份@H_502_1@
month from now()); date_part --------- 4 (day from 2013-04-13'); date_part --------- 13 (SELECT EXTRACT(DAY FROM INTERVAL 40 days 1 minute40 ( 3.3 查看今天是一年中的第几天@H_502_1@
select extract(doy --------- 102 ( 3.4 查看现在距1970-01-01 00:00:00 UTC 的秒数@H_502_1@
select extract(epoch from now()); date_part ---------------- 1365755907.94474 ( 3.5把epoch 值转换回时间戳@H_502_1@
SELECT TIMESTAMP WITH TIME ZONE epoch' + 1369755555 * INTERVAL 1 second'; ?column? 28 23:15 以上是基本的PG时间/日期函数使用,可满足一般的开发运维应用。@H_502_1@

猜你在找的Postgre SQL相关文章