Question

I have a timestamp column where I track when an external sensor records a reading. This column goes to the microsecond, but I would like to truncate the data to the decisecond for grouping purposes.

This truncate function works great, but only allows resolution of millisecond or microsecond. I just need to trim my data to the decisecond to account for errors in my collection process.

Is there a way to return timestamp columns trimmed to the decisecond?

Was it helpful?

Solution

Replace Now() (current time) with column of your choice:

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)

Note that cast to numeric is required as extract() returns double precision and trunc(x, y) accepts only numeric (see documentation)

With column named mytime this would be:

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

Another option would be to truncate 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))

With column named mytime this would be:

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

Documentation: extract, epoch, to_timestamp

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top