Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

前端 未结 7 1441
南旧
南旧 2020-11-28 17:55

I want to extract just the date part from a timestamp in PostgreSQL.

I need it to be a postgresql DATE type so I can insert it into another table that e

相关标签:
7条回答
  • 2020-11-28 18:29

    Just do select date(timestamp_column) and you would get the only the date part. Sometimes doing select timestamp_column::date may return date 00:00:00 where it doesn't remove the 00:00:00 part. But I have seen date(timestamp_column) to work perfectly in all the cases. Hope this helps.

    0 讨论(0)
  • 2020-11-28 18:32

    You can cast your timestamp to a date by suffixing it with ::date. Here, in psql, is a timestamp:

    # select '2010-01-01 12:00:00'::timestamp;
          timestamp      
    ---------------------
     2010-01-01 12:00:00
    

    Now we'll cast it to a date:

    wconrad=# select '2010-01-01 12:00:00'::timestamp::date;
        date    
    ------------
     2010-01-01
    

    On the other hand you can use date_trunc function. The difference between them is that the latter returns the same data type like timestamptz keeping your time zone intact (if you need it).

    => select date_trunc('day', now());
           date_trunc
    ------------------------
     2015-12-15 00:00:00+02
    (1 row)
    
    0 讨论(0)
  • 2020-11-28 18:33

    Use the date function:

    select date(timestamp_field) from table
    

    From a character field representation to a date you can use:

    select date(substring('2011/05/26 09:00:00' from 1 for 10));
    

    Test code:

    create table test_table (timestamp_field timestamp);
    insert into test_table (timestamp_field) values(current_timestamp);
    select timestamp_field, date(timestamp_field) from test_table;
    

    Test result:

    pgAdmin result

    pgAdmin result wide

    0 讨论(0)
  • 2020-11-28 18:33

    In postgres simply : TO_CHAR(timestamp_column, 'DD/MM/YYYY') as submission_date

    0 讨论(0)
  • 2020-11-28 18:34
    CREATE TABLE sometable (t TIMESTAMP, d DATE);
    INSERT INTO sometable SELECT '2011/05/26 09:00:00';
    UPDATE sometable SET d = t; -- OK
    -- UPDATE sometable SET d = t::date; OK
    -- UPDATE sometable SET d = CAST (t AS date); OK
    -- UPDATE sometable SET d = date(t); OK
    SELECT * FROM sometable ;
              t          |     d      
    ---------------------+------------
     2011-05-26 09:00:00 | 2011-05-26
    (1 row)
    

    Another test kit:

    SELECT pg_catalog.date(t) FROM sometable;
        date    
    ------------
     2011-05-26
    (1 row)
    
    SHOW datestyle ;
     DateStyle 
    -----------
     ISO, MDY
    (1 row)
    
    0 讨论(0)
  • 2020-11-28 18:35

    This works for me in python 2.7

     select some_date::DATE from some_table;
    
    0 讨论(0)
提交回复
热议问题