Skip to content

Instantly share code, notes, and snippets.

@gajus
Created May 18, 2018 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gajus/1ffbcc7b042845e421f7949f9eb7d679 to your computer and use it in GitHub Desktop.
Save gajus/1ffbcc7b042845e421f7949f9eb7d679 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION round_to_interval (input_timestamp timestamp with time zone, interval_size interval) RETURNS timestamp with time zone AS $$
DECLARE
interval_in_seconds CONSTANT int := extract('epoch' FROM interval_size);
BEGIN
RETURN to_timestamp(trunc(extract('epoch' FROM (input_timestamp - '1 microsecond'::interval)))::int / interval_in_seconds * interval_in_seconds + interval_in_seconds);
END
$$
LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment