Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL 9.5: Convert intervals INTO milliseconds

Tags:

postgresql

I have the following two dates which is in the form of varchar(50).

Date1: 2016-11-24 12:38:29.123

Date2: 2016-04-22 11:44:55

First date that is Date1 contains milliseconds and Date2 contains till seconds. So i did casting to get up to seconds from both dates.

Using:

SELECT ('2016-11-24 12:38:29.123'::timestamp(0) - '2016-04-22 11:44:55'::timestamp(0));

Output:

216 days 00:53:34

Note: Now i want to convert 216 days 00:53:34 into milliseconds.

My try:

SELECT EXTRACT(MILLISECONDS FROM(CAST('2016-11-24 12:38:29.123' AS timestamp(0)) - CAST('2016-04-22 11:44:55' AS timestamp(0))));

Output:

34000

Problem: 34000 is not the exact milliseconds of 216 days 00:53:34.

like image 526
MAK Avatar asked Nov 24 '16 06:11

MAK


People also ask

How does interval work 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 change the format of a timestamp in PostgreSQL?

You can specify double colons (::) to cast a DATETIME value to a DATE value. You can combine TO_CHAR() and the Now() function to convert the current timestamp into the specified format.

What is now () in PostgreSQL?

What is PostgreSQL Now Function? The Now() function is used to return the current date and time of the time zone (default or user-defined). Its return type is the timestamp with the time zone.

What is the format of timestamp in PostgreSQL?

The output format of the date/time types can be set to one of the four styles ISO 8601, SQL (Ingres), traditional POSTGRES (Unix date format), or German. The default is the ISO format. (The SQL standard requires the use of the ISO 8601 format.


1 Answers

You are looking for epoch which returns the number of seconds stored in the interval.

SELECT extract(epoch from timestamp '2016-11-24 12:38:29.123' - timestamp '2016-04-22 11:44:55');

returns: 18665614

like image 188
a_horse_with_no_name Avatar answered Dec 13 '22 18:12

a_horse_with_no_name