如何在 PostgreSQL 存储过程中生成以毫秒为单位的时间?

Jér*_*nge 2 postgresql stored-procedures timestamp

我一直在阅读有关时间戳的 Postgres 文档,但我仍然有点困惑。

我需要存储当前时间和 1970 年 1 月 1 日午夜之间的时刻(以毫秒为单位)(类似于Java中定义的时刻,但我没有使用 Java)。

如果我正确阅读文档,我相信我必须使用CURRENT_TIMESTAMP,因为它包含时区。正确的?

有人可以解释如何创建一个存储过程,将该时间戳转换为我想要的毫秒(以及反向函数)吗?

动机:我知道在选择行时可以使用类似EXTRACTon的东西CURRENT_TIMESTAMP,但这种转换比以毫秒为单位存储时间更昂贵。我准备将我的时刻存储到bigint. 比较时刻或计算时间差会更快。

小智 5

我知道在选择行时可以使用诸如 EXTRACT on CURRENT_TIMESTAMP 之类的东西

您不需要extract为了获取数据:

select *
from your_table
where timestamp_column >= timestamp '2007-08-24 18:34:01';
Run Code Online (Sandbox Code Playgroud)

会很高兴地使用索引moment_in_time并且非常高效 - 事实上与

select *
from your_table
where milliseconds_column >= 1187906400000;
Run Code Online (Sandbox Code Playgroud)

现在看看这两个语句,并告诉我您立即了解哪一个语句查询将返回什么。

如果您的应用程序确实需要这些毫秒,那么您始终可以执行以下操作:

select some_col, 
       other_col,
       extract(epoch from timestamp_column) * 1000 as millis
from your_table
where timestamp_column >= timestamp '2007-08-24 18:34:01';
Run Code Online (Sandbox Code Playgroud)

再说一遍,我几乎 100% 确定您不会看到以下方面的任何性能差异:

select some_col, 
       other_col,
       milliseconds_column
from your_table
where  milliseconds_column >= 1187906400000;
Run Code Online (Sandbox Code Playgroud)

另外:如果您确实存储了毫秒并且想要显示真实日期,则始终需要应用额外的转换:

select some_col, 
       other_col,
       to_char(timestamp_column, 'yyyy-mm-dd') as the_date
from your_table
where timestamp_column >= timestamp '2007-08-24 18:34:01';
Run Code Online (Sandbox Code Playgroud)

select some_col, 
       other_col,
       to_char(to_timestamp(milliseconds_column / 1000), 'yyyy-mm-dd) as the_date
from your_table
where  milliseconds_column >= 1187906400000;
Run Code Online (Sandbox Code Playgroud)

第二个比第一个慢,但需要更多的打字,并使代码更难阅读。

编辑

如何创建一个存储过程,将该时间戳转换为我想要的毫秒(以及反向函数)?

您不需要编写自己的函数:

  1. 将时间戳转换为毫秒:
    extract(epoch from current_timestamp) * 1000 + extract(milliseconds from current_timestamp)
  2. 将毫秒转换为时间戳:to_timestamp(1187980443530 / 1000)

总结一下:

使用timestamp专栏,不用担心性能。