Search code examples
postgresqldatetimeepochjulian-date

Convert Julian Date to Timestamp in PostgreSQL


I have a table full of "Julian Dates", that is the number of days and seconds away from 1/1/2035. I need to convert these to normal postgres timestamps. Can anyone help?

--Converts '2000-06-20 12:30:15' into an Epoch time base which gives a result of -12612.478993055556
select (EXTRACT(epoch FROM ('2000-06-20 12:30:15'::timestamp - '2035-01-01 00:00:00'))/86400.00) as run_ts

--Question, how to convert -12612.478993055556 back into '2000-06-20 12:30:15'
select -12612.478993055556 ??? as run_ts

Solution

  • You can use to_timestamp() to convert an epoch to a timestamp.

    The epoch you posted does not correspond to 2000-06-20, as you have removed another date 2035-01-01 from it.

    select (EXTRACT(epoch FROM ('2000-06-20 12:30:15'::timestamp )));
     date_part
    -----------
     961504215
    (1 row)
    
    select to_timestamp(961504215);
          to_timestamp
    ------------------------
     2000-06-20 08:30:15-04
    (1 row)
    
    
    select to_timestamp(-12612.478993055556);
             to_timestamp
    -------------------------------
     1969-12-31 15:29:47.521007-05
    (1 row)
    

    EDIT

    Since you are not considering a true epoch but really a difference between two dates, you can simply add this difference to the reference date. You can use the day interval to remove the need to multiply by 86400 (seconds/day)

    select  '2035-01-01 00:00:00'::timestamp + interval '1' day *  -12612.478993055556;
          ?column?
    ---------------------
     2000-06-20 12:30:15