Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract seconds from postgres datetime

Tags:

postgresql

Say I have column of type dateTime with value "2014-04-14 12:17:55.772" & I need to subtract seconds "2" seconds from it to get o/p like this "12:17:53".

like image 374
user1298426 Avatar asked Apr 14 '14 14:04

user1298426


People also ask

How do I subtract two timestamps in PostgreSQL?

To calculate the difference between the timestamps in PostgreSQL, simply subtract the start timestamp from the end timestamp. Here, it would be arrival - departure . The difference will be of the type interval , which means you'll see it in days, hours, minutes, and seconds.

What is interval in PostgreSQL?

In PostgreSQL the interval data type is used to store and manipulate a time period. It holds 16 bytes of space and ranging from -178, 000, 000 years to 178, 000, 000 years. It also has additional attribute called “precision (denoted by p)” that can be used to set the level of precision in the query results.

How do I subtract a day from a timestamp in SQL?

In SQL Server, you can subtract or add any number of days using the DATEADD() function. The DATEADD() function takes three arguments: datepart , number , and date . Here, the value of datepart is day , because the unit of time you want to subtract is day.


1 Answers

select '2014-04-14 12:17:55.772'::timestamp - interval '2 seconds';

For greater flexibility it is possible to mutiply the interval

select '2014-04-14 12:17:55.772'::timestamp - 2 * interval '1 second';

If you want to truncate to the second

select date_trunc(
    'second', 
    '2014-04-14 12:17:55.772'::timestamp - interval '2 seconds'
);
like image 75
Clodoaldo Neto Avatar answered Sep 23 '22 19:09

Clodoaldo Neto