Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: Update date and retain time from timestamp

I have a field1 with timestamp, datatype and values format is 2016-02-23 12:01:30.

I'm running the query:

UPDATE <table> set field1 = '2015-12-31'::timestamp::date where .....

The output changes to:

  2015-12-31 00:00:00

It converts the time to all zero's. How to change the date and retain the timestamp?

like image 506
Arnold Cristobal Avatar asked Feb 23 '16 05:02

Arnold Cristobal


People also ask

How do I save a timestamp in PostgreSQL?

First we create a table that has both timestamp and timestamptz columns using the below command: CREATE TABLE timestamp_demo (ts TIMESTAMP, tstz TIMESTAMPTZ); Then we will set the time zone of database server to Asia/Calcutta as below: SET timezone = 'Asia/Calcutta';


1 Answers

Try this:

UPDATE mytable 
SET field1 = '2015-12-31'::timestamp + 
             EXTRACT(HOUR FROM field1) * INTERVAL '1 HOUR' +
             EXTRACT(MINUTE FROM field1) * INTERVAL '1 MINUTE' +
             EXTRACT(SECOND FROM field1) * INTERVAL '1 SECOND' 
WHERE ...

Demo here

like image 127
Giorgos Betsos Avatar answered Oct 04 '22 17:10

Giorgos Betsos