Re: Strategies for converting UTC data to local windows for arbitrary resolutions and timezones - Mailing list pgsql-general

From Tom Lane
Subject Re: Strategies for converting UTC data to local windows for arbitrary resolutions and timezones
Date
Msg-id 2582288.1696428710@sss.pgh.pa.us
Whole thread Raw
In response to Re: Strategies for converting UTC data to local windows for arbitrary resolutions and timezones  (Steve Crawford <scrawford@pinpointresearch.com>)
Responses Re: Strategies for converting UTC data to local windows for arbitrary resolutions and timezones  (Marian Wendt <marian.wendt@yahoo.com>)
List pgsql-general
Steve Crawford <scrawford@pinpointresearch.com> writes:
> On Tue, Oct 3, 2023 at 7:33 PM Lincoln Swaine-Moore <lswainemoore@gmail.com>
> wrote:
>> 5) Ideally, the solution would not involve messing with the
>> server/connection's value of timezone. (Though I would be interested if
>> there was a solution that relaxed this constraint and was relatively
>> safe/compatible with transactions and psycopg2.)

> Note that setting the time zone is a client/connection setting so if you
> set it within a transaction, it will stay set when the transaction
> concludes. But time manipulation is tricky and trying to DIY reinvent the
> wheel is painful and often buggy. Let PostgreSQL do the work for you.

Expanding on that philosophy: you should be able to set the timezone
locally within a function, so that it wouldn't be that hard to make a
wrapper for generate_series that emulates the 4-argument version added
in v16.

Rather than messing with manually saving and restoring the prevailing
zone, I'd let the function SET infrastructure do it for me.  Sadly,
that SET clause only takes literal constant arguments, so it'd go
roughly like this:

create function generate_series(timestamptz, timestamptz, interval, text)
returns setof timestamptz
strict immutable language plpgsql as
$$
begin
  perform set_config('timezone', $4, true);
  return query select generate_series($1, $2, $3);
end
$$ set timezone = 'UTC';

Setting the zone to UTC is a useless step, but that triggers
restoring the previous zone when the function exits; simpler
and probably faster than coding the save/restore explicitly.

Side note: whether this is really "immutable" is a matter for
debate, since time zone definitions tend to change over time.
But we chose to mark the new 4-argument version that way,
so you might as well do so too.

            regards, tom lane



pgsql-general by date:

Previous
From: "Johnson, Bruce E - (bjohnson)"
Date:
Subject: Re: [EXT]Re: Strange error trying to import with Ora2PG
Next
From: Marian Wendt
Date:
Subject: Re: Strategies for converting UTC data to local windows for arbitrary resolutions and timezones