Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: how to convert from Unix epoch to date?

The statement gives me the date and time.

How could I modify the statement so that it returns only the date (and not the time)?

SELECT to_timestamp( TRUNC( CAST( epoch_ms AS bigint ) / 1000 ) ); 
like image 441
sid_com Avatar asked May 17 '13 13:05

sid_com


People also ask

How do I convert Epoch to date?

Because our Epoch time is specified in milliseconds, we may convert it to seconds. To convert milliseconds to seconds, first, divide the millisecond count by 1000. Later, we use DATEADD() to add the number of seconds since the epoch, which is January 1, 1970 and cast the result to retrieve the date since the epoch.

How do I convert epoch time to manual date?

You can take an epoch time divided by 86400 (seconds in a day) floored and add 719163 (the days up to the year 1970) to pass to it. Awesome, this is as manual as it gets.

How do I convert text to date in PostgreSQL?

The TO_DATE function in PostgreSQL is used to converting strings into dates. Its syntax is TO_DATE(text, text) and the return type is date. The TO_TIMESTAMP function converts string data into timestamps with timezone. Its syntax is to_timestamp(text, text) .

What is Epoch in PostgreSQL?

Posted on 15th August 2022. YES, you can convert EPOCH to Timestamp by merely switching to the present Timestamp in PostgreSQL DBMS. EPOCH time is nothing but the number of seconds from 00:00:00 UTC on 1 January 1970. Till date, without adding the extra leap year days, this is considered.


1 Answers

You use to_timestamp function and then cast the timestamp to date

 select to_timestamp(epoch_column)::date; 

More details:

/* Current time */  select now();  -- returns timestamp  /* Epoch from current time;    Epoch is number of seconds since 1970-01-01 00:00:00+00 */  select extract(epoch from now());   /* Get back time from epoch */  -- Option 1 - use to_timestamp function  select to_timestamp( extract(epoch from now()));  -- Option 2 - add seconds to 'epoch'  select timestamp with time zone 'epoch'           + extract(epoch from now()) * interval '1 second';  /* Cast timestamp to date */  -- Based on Option 1  select to_timestamp(extract(epoch from now()))::date;  -- Based on Option 2  select (timestamp with time zone 'epoch'            + extract(epoch from now()) * interval '1 second')::date;  

In your case:

 select to_timestamp(epoch_ms / 1000)::date; 

PostgreSQL Docs

like image 192
Tomas Greif Avatar answered Sep 29 '22 07:09

Tomas Greif