美文网首页
Postgresql 日期函数

Postgresql 日期函数

作者: zhiwliu | 来源:发表于2022-02-09 16:38 被阅读0次

取时间

  1. now()/current_timestamp: 这两个是等价的;
  2. timeofday(): 包括了日期,星期; 这个函数跟上面两个的不同是:
    在一个事务里,now(),current_timestamp不管执行多少次都是同一个值;
    但是timeofday()每次都是不完全一样的
  3. select current_date, current_time; 取当前日期和当前时间

时间截取(extract)

field可以是year,month,day,hour,minute,second,epoch(转成了timestamp,也就是自从1970-01-01距离的秒数);
也可以是dof(一年的第几天)
具体参数: https://www.postgresqltutorial.com/postgresql-extract/

select extract(year from now())

时间计算

通过interval加减, 下面的SQL是把interval关键字给省略了;

auditdb=# select now() + '1m';              
           ?column?            
-------------------------------
 2022-02-09 08:17:46.622117+00
(1 row)

auditdb=# select now() + '1m -1d';
           ?column?            
-------------------------------
 2022-02-08 08:17:55.529641+00
(1 row)
auditdb=# select now() + '1m -1h';   
           ?column?            
-------------------------------
 2022-02-09 07:18:09.819771+00

取两个时间差

取两个时间之间的秒数

auditdb=# select extract(epoch FROM ('2020-10-13'::timestamp - '2020-10-12'::timestamp));       
 date_part 
-----------
     86400

取两个日期之间的天数

auditdb=# select '2020-10-13'::date - '2020-10-14'::date;                                
 ?column? 
----------
       -1
(1 row)

auditdb=# select '2020-10-13'::date - '2020-10-14 08:24:24'::date;
 ?column? 
----------
       -1

取当前月的第一天

auditdb=# select date_trunc('month',generate_series(date'2021-1-10','2021-08-03', interval '1 month'));
       date_trunc
------------------------
 2021-01-01 00:00:00+00
 2021-02-01 00:00:00+00
 2021-03-01 00:00:00+00
 2021-04-01 00:00:00+00
 2021-05-01 00:00:00+00
 2021-06-01 00:00:00+00
 2021-07-01 00:00:00+00

取上个月的最后一天

select date_trunc('month',generate_series(date'2021-1-10','2021-08-03', interval '1 month'))-interval '1 day';
        ?column?
------------------------
 2020-12-31 00:00:00+00
 2021-01-31 00:00:00+00
 2021-02-28 00:00:00+00
 2021-03-31 00:00:00+00
 2021-04-30 00:00:00+00
 2021-05-31 00:00:00+00
 2021-06-30 00:00:00+00

相关文章

  • Postgresql 日期函数

    取时间 now()/current_timestamp: 这两个是等价的; timeofday(): 包括了日期,...

  • 在PostgreSQL 和 Hive中生成日期序列

    ## 在PostgreSQL 和 Hive中生成日期序列 ### Postgresql实现日期序列 在postgr...

  • postgresql时间差计算

    记一笔postgresql在时间计算上的方法。 计算时间差date_part() 函数用于返回日期/时间的单独部分...

  • postgresql函数

    1 若count != 1时,抛出异常并返回 2 循环批量插入或更新数据 3 使用主键-1 4 双层循环

  • 211111:用Java实现数字转汉字-postgreSQL中对

    一、 用Java实现数字转汉字 二、postgreSQL获得两个日期之间的时间差的天数 三、postgreSQL给...

  • 日期函数

    一、日期函数: 根据这一组函数可以将日期(YMD)和时间(hms)随心所欲的拆分或组合 1、基本用法 ⑴日期函数 ...

  • 日期函数

    datedif函数 datedif函数解释: datedif(起始日期,终止日期,间隔单位)计算两个日期的间隔 计...

  • 日期函数

    日期函数主要用于计算星期、工龄、年龄、账龄、利息,以及计算某个时间段的数据汇总等等。下面是一些常用日期函数的...

  • 日期函数

    1、基本用法 1.1 =TODAY() 2018-12-2 当天日期,随时间的变化而变化 , 快捷键 Ctrl...

  • 日期函数

    日期函数 (YEAR MONTH DATEDIF ) 12月2日 本节学习目录(图一) - 日期函数的基本结构 Y...

网友评论

      本文标题:Postgresql 日期函数

      本文链接:https://www.haomeiwen.com/subject/thowkrtx.html