PostgreSQL 常见时间日期处理

CodeCipherX
• 阅读 3542

前言

在实际业务开发过程中,通常会遇到对时间日期相关的处理,这里列出一些常见的时间日期处理方法。

1. 时间戳带时区和不带时区

创建表字段时,指定带时区时间日期数据类型

postgres=# CREATE TABLE tab_test(id serial,app_name varchar,app_release_date timestamp with time zone default now());
    CREATE TABLE
    postgres=# INSERT INTO tab_test VALUES(1,'app');
    INSERT 0 1
    postgres=# select * from tab_test;
     id | app_name |       app_release_date        
    ----+----------+-------------------------------
      1 | app      | 2021-10-11 15:24:05.730805+08
    (1 row)

修改表字段为不带时区的数据类型


postgres=# alter table tab_test alter column app_release_date set  data type timestamp without time zone;
    ALTER TABLE
    postgres=# alter table tab_test alter column app_release_date set default now();
    ALTER TABLE
    postgres=# insert into tab_test values(2,'app2');
    INSERT 0 1
    postgres=# select * from tab_test;
     id | app_name |      app_release_date      
    ----+----------+----------------------------
      1 | app      | 2021-10-11 15:24:05.730805
      2 | app2     | 2021-10-11 15:29:03.749597
    (2 rows)

2.时间日期函数转换为带时区和不带时区的操作

返回当前时间戳的函数


postgres=# select current_timestamp,clock_timestamp();
           current_timestamp       |        clock_timestamp        
    -------------------------------+-------------------------------
     2021-10-11 15:39:17.720835+08 | 2021-10-11 15:39:17.720974+08
    (1 row)

返回当前时间戳函数不带时区


postgres=# select current_timestamp::timestamp without time zone,clock_timestamp()::timestamp without time zone;
         current_timestamp      |      clock_timestamp       
    ----------------------------+----------------------------
     2021-10-11 15:40:25.859267 | 2021-10-11 15:40:25.859363
    (1 row)  

3.将时间戳转换为从1970-01-01开始时的整数

将当前时间转换为自1970-01-01开始到当前的整数


postgres=# select extract(epoch from now());
     date_part     
    -------------------
    1633938422.406166
    (1 row)

上面函数 now() 是带有时区的,是否带时区和不带时区转换的整数不一致呢?


postgres=# select extract(epoch from now()),extract(epoch from now()::timestamp without time zone);
     date_part     |     date_part     
    -------------------+-------------------
    1633938525.014723 | 1633967325.014723
    (1 row)

通过上面的示例,可以看出,如果将时间戳转换为整型,带有时区和不带有时区的值是不一样的。

4.输出时间不带精度


postgres=# select current_timestamp(0),current_time(0),localtime(0),localtimestamp(0);
     current_timestamp    | current_time | localtime |   localtimestamp    
  ------------------------+--------------+-----------+---------------------
   2021-10-11 16:00:56+08 | 16:00:56+08  | 16:00:56  | 2021-10-11 16:00:56
  (1 row)

在 PostgreSQL 中,时间戳函数和时间函数默认保留6位精度,只需要将时间精度保留为0即可去除精度。

5.将输出不带精度的时间转换为整数


postgres=# select extract(epoch from current_timestamp(0)) ;
   date_part  
  ------------
   1634200047
  (1 row)

7.将时间按照时间域进行分解

将时间按照时间域进行分解,有两个函数可以实现,一个是extract函数,一个是date_part函数


postgres=# select date_part('month',now()),extract('month' from now());
   date_part | date_part 
  -----------+-----------
          10 |        10
  (1 row)

8.生成随机根据传入的参数生成随机日期


create or replace function random_date(date,date,integer,integer)
  returns date
  as
  $function$
  --声明随机数
  declare
    random_range integer;
    random_days   integer;
    random_start_date date;
  begin
    --指定随机范围
    random_range = $4 - $3;
    --随机天数设置
    random_days = trunc(random()*random_range);
    --随机日期需要从传入参数的起始值开始
    random_start_date = $1 + random_days;
    if random_start_date > $2 then
      raise notice '随机日期不能大于结束日期';
      return $2;
    else
      return random_start_date;
    end if;
  end;
    
  $function$
  language plpgsql;

  postgres=# select random_date('2001-01-02','2008-02-03',100,3000);
   random_date 
  -------------
   2006-08-03
  (1 row)

  postgres=# select random_date('2001-01-02','2008-02-03',100,3000);
   random_date 
  -------------
   2004-07-24
  (1 row)

  postgres=# select random_date('2001-01-02','2008-02-03',100,30000);
  NOTICE:  随机日期不能大于结束日期
   random_date 
  -------------
   2008-02-03
  (1 row)

9.测试随机日期插入数据


postgres=# create table tab_random_date(id serial,p_date date);
  CREATE TABLE
  postgres=# insert into tab_random_date(p_date) select random_date('2001-01-02','2008-02-03',100,id) from generate_series(1,1000) as id;
  INSERT 0 1000

  postgres=# select count(*),p_date from tab_random_date group by p_date;
   count |   p_date   
  -------+------------
       3 | 2002-01-23
       1 | 2001-10-14
       6 | 2001-01-29
       1 | 2002-04-19
       1 | 2002-05-17
       4 | 2000-12-16
点赞
收藏
评论区
推荐文章
Karen110 Karen110
3年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
爆赞!2021互联网大厂Java面经合集
前言本系列的目的是明明白白、彻彻底底的搞定日期/时间处理的几乎所有case。上篇文章铺设所有涉及到的概念解释,例如GMT、UTC、夏令时、时间戳等等,若你还没看过,不仅强烈建议而是强制建议你前往用花5分钟看一下,因为日期时间处理较为特殊,实战必须基于对概念的了解,否则很可能依旧雾里看花。说明:日期/时间的处理是日常开发非常常见的老大难,究其原因就是对日期时
皕杰报表(关于日期时间时分秒显示不出来)
在使用皕杰报表设计器时,数据据里面是日期型,但当你web预览时候,发现有日期时间类型的数据时分秒显示不出来,只有年月日能显示出来,时分秒显示为0:00:00。1.可以使用tochar解决,数据集用selecttochar(flowdate,"yyyyMMddHH:mm:ss")fromtablename2.也可以把数据库日期类型date改成timestamp
Souleigh ✨ Souleigh ✨
4年前
python时间模块的使用 white_study
前言:在开发中经常会与时间打交道,如:获取事件戳,时间戳的格式化等,这里简要记录一下python操作时间的方法。python中常见的处理时间的模块:time:处理时间的模块,如获取时间戳,格式化日期等datetime:date和time的结合体,处理日期和时间calendar:日历相关的模块,如:处理年历/月历tim
Karen110 Karen110
3年前
​一篇文章总结一下Python库中关于时间的常见操作
前言本次来总结一下关于Python时间的相关操作,有一个有趣的问题。如果你的业务用不到时间相关的操作,你的业务基本上会一直用不到。但是如果你的业务一旦用到了时间操作,你就会发现,淦,到处都是时间操作。。。所以思来想去,还是总结一下吧,本次会采用类型注解方式。time包importtime时间戳从1970年1月1日00:00:00标准时区诞生到现在
Wesley13 Wesley13
3年前
Android中Calendar与Date的区别以及消除时区对日期操作影响的方法
Android中Calendar与Date的区别以及消除时区对日期操作影响的方法在Android中的日期操作常用的有三种方式,分别是:1.Date类型2.Calendar类型3.Unix时间戳其中,Unix时间戳在计算上最为方便和灵活,效率也高;而Date和Calendar则在一些具体的日期计算上更为便利。其中,在进行日
Wesley13 Wesley13
3年前
Java日期时间API系列31
  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前
Stella981 Stella981
3年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
3年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
小万哥 小万哥
1年前
SQL 日期处理和视图创建:常见数据类型、示例查询和防范 SQL 注入方法
SQL处理日期在数据库操作中,处理日期是一个关键的方面。确保插入的日期格式与数据库中日期列的格式匹配至关重要。以下是一些常见的SQL日期数据类型和处理方法。SQL日期数据类型MySQL日期数据类型DATE格式为YYYYMMDDDATETIME格式为YYYY