Postgres:如何从unix时代转换为日期?

sid*_*com 38 sql postgresql date type-conversion epoch

声明给了我日期和时间.

我怎样才能修改语句,使其仅返回日期?

SELECT to_timestamp( TRUNC( CAST( epoch_ms AS bigint ) / 1000 ) );
Run Code Online (Sandbox Code Playgroud)

Tom*_*eif 69

/* Current time */
 select now(); 

/* 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; 

 /* For column epoch_ms */
 select to_timestamp(extract(epoch epoch_ms))::date;
Run Code Online (Sandbox Code Playgroud)

PostgreSQL文档

  • 好吧,我逐字运行了“ select to_timestamp(extract(epoch epoch_ms)):: date;”,它在epoch_ms附近给出了语法错误。我去寻找其他解决方案,并最终为我工作了'SELECT TIMESTAMP'epoch'+(start_dt)* INTERVAL'1 second'as starts_on`。您能解释一下“ TIMESTAMP”和“ to_timestamp()”之间的区别吗? (3认同)
  • TIMESTAMP只是列类型,其中to_timestamp是一个内置函数,该函数将unix纪元转换为从'1970-01-01 00:00:00 + 00'开始的时间戳计算 (2认同)

小智 26

select to_timestamp(cast(epoch_ms/1000 as bigint))::date
Run Code Online (Sandbox Code Playgroud)

为我工作


Ste*_*tta 10

在 Postgres 10 上:

SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)