在 postgresql 中使用 nanosec 存储时间戳的最优雅方法是什么?

Csu*_*usz 6 sql postgresql datetime timestamp date

不幸的是,postgresql 时间戳类型只能以微秒精度存储时间戳,但我也需要纳秒。

PostgreSQL - 8.5。日期/时间类型:

时间戳和间隔接受可选的精度值 p,它指定秒字段中保留的小数位数。默认情况下,没有明确的精度限制。对于时间戳和间隔类型,p 的允许范围是从 0 到 6。

我需要 7 个:

0,000 000 001 [十亿分之一]纳秒[ns]

0,000 001 [ 百万分之一 ] 微秒 [ µs ]

0,001 [千分位] 毫秒 [ ms ]

0.01 [百分之一] 厘秒 [ cs ]

1.0 秒 [ s ]

有没有优雅有效的方法来处理这个问题?

编辑:也许将时间戳存储在 bigint 中?

kli*_*lin 5

用作numeric纳米时间戳的基本类型。该函数将数值转换为其文本时间戳表示形式:

create or replace function nanotimestamp_as_text(numeric)
returns text language sql immutable as $$
    select concat(to_timestamp(trunc($1))::timestamp::text, ltrim(($1- trunc($1))::text, '0'))
$$;
Run Code Online (Sandbox Code Playgroud)

在不需要超精度的情况下,您还可以轻松地将数值转换为常规时间戳,例如:

with my_data(nano_timestamp) as (
    select 1508327235.388551234::numeric
)

select 
    to_timestamp(nano_timestamp)::timestamp,
    nanotimestamp_as_text(nano_timestamp)
from my_data;

        to_timestamp        |     nanotimestamp_as_text     
----------------------------+-------------------------------
 2017-10-18 13:47:15.388551 | 2017-10-18 13:47:15.388551234
(1 row)
Run Code Online (Sandbox Code Playgroud)