Postgres截断时间戳截断到Decisecond

时间:2014-02-24 00:54:59

标签: postgresql timestamp trim truncate

我有一个timestamp列,用于跟踪外部传感器何时记录读数。此列转到microsecond,但我想将数据截断为decisecond以进行分组。

truncate function效果很好,但只允许解析millisecondmicrosecond。我只需要将我的数据修剪为decisecond以解决我的收集过程中的错误。

有没有办法将timestamp列修剪为decisecond

1 个答案:

答案 0 :(得分:0)

Now()(当前时间)替换为您选择的列:

select 
  -- current time
  now(), 

  -- current time truncated to minutes
  date_trunc('minute', Now()), 

  -- seconds from timestamp, including decimal part
  extract(seconds from Now()),

  -- seconds truncated to first decimal digit (results in seconds and decisecond)
  trunc((extract(seconds from Now()))::numeric, 1),

  -- add time truncated to minutes and seconds truncated to first decimal digit
  date_trunc('minute', Now()) 
     + interval '1 second' * trunc((extract(seconds from Now()))::numeric, 1)

请注意,由于numeric返回extract()double precision仅接受trunc(x, y)(请参阅documentation)numeric >

对于名为mytime的列,这将是:

  date_trunc('minute', mytime) 
     + interval '1 second' * trunc((extract(seconds from mytime))::numeric, 1)

另一种选择是截断epoch

select 
  -- current time
  now(), 

  -- epoch - number of seconds since epoch beginning, including decimal part
  extract(epoch from Now()),

  -- truncated to first decimal digit
  trunc((extract(epoch from Now()))::numeric, 1),

  -- converted back to timestamp
  to_timestamp(trunc((extract(epoch from Now()))::numeric, 1))

对于名为mytime的列,这将是:

  to_timestamp(trunc((extract(epoch from mytime))::numeric, 1))    

文档:extractepochto_timestamp