1

Can any body tell how to remove or skip the millisecond part while inserting the current time to the timestamp column in Postgres database table. Actually the column that holds the data type timestamp without timezone and default is set to now() i.e. it will take the current date and time.

It inserts right date and time but it puts the millisecond part for example the format that gets entered is "2015-01-07 10:27:44.234534" which has millisecond part i.e 234534 which I don't want to be inserted. I only want the the data that is to be inserted is as "2015-01-07 10:27:44". Can any body let me know without changing the data type of that column how to insert the current date and time skipping the millisecond part.

bikashphp
  • 165
  • 3
  • 10

2 Answers2

8

Change your default to strip off the milliseconds:

create table foo 
(
  id integer not null primary key,
  created_at timestamp default date_trunc('second', current_timestamp)
);

Or to change the default for an existing table:

alter table foo 
   alter column created_at set default date_trunc('second', current_timestamp);

To change the existing values, you can use:

update foo 
  set created_at = date_trunc('second', created_at)
where created_at is not null;

Instead of using date_trunc you can also just cast the value: created_at::timestamp(0) for the update statement, or current_timestamp::timestamp(0) in the default value.

2

As alternative, if you could modify the data type of that column, you could insert by default the CURRENT_TIME:

    CREATE TABLE my_table (
                    col1 TEXT,
                    col2 INTEGER,
                    ts TIMESTAMP(0) DEFAULT CURRENT_TIMESTAMP
                    );

The 0 between parentheses is saying that you don't want any milliseconds. See the documentation for further details.

eshirvana
  • 23,227
  • 3
  • 22
  • 38
J0ANMM
  • 7,849
  • 10
  • 56
  • 90