Getting date with timezone offset

前端 未结 3 1034
情深已故
情深已故 2020-12-15 07:02

I am trying to extract the date from a query in postgres. The timestamp is stored as UTC, so if I have 1/1/2014 02:00:00, I want the date in pacific time, to be 12/31/2013,

相关标签:
3条回答
  • 2020-12-15 07:28

    If it is timestamp without time zone you need first to tell it to use the UTC time zone and then convert to another time zone:

    SELECT '1-1-2014 02:00:00'::timestamp at time zone 'UTC' at time zone 'America/Los_Angeles';
          timezone       
    ---------------------
     2013-12-31 18:00:00
    
    0 讨论(0)
  • 2020-12-15 07:29

    If 'America/Los_Angeles' is your current time zone (timezone setting of the current session) then just tell Postgres the time zone of the timestamp.

    SELECT ('2014-01-01 02:00:00'::timestamp AT TIME ZONE 'UTC')::date;
    

    The cast to date is based on the current time zone and works automatically as desired.

    If the current time zone can be something else, you need to be explicit like @Clodoaldo demonstrates.

    The proper solution would be to store a timestamp with time zone (timestamptz) to begin with, then you can just cast to date:

    SELECT '2014-01-01 02:00:00+0'::timestamptz::date;
    

    About timestamps in Postgres:

    • Ignoring time zones altogether in Rails and PostgreSQL

    Recent related answer with more details (also dealing with indexes):

    • Optimize/Index Timezone Query
    0 讨论(0)
  • 2020-12-15 07:43

    I figured it out, using the interval, I can subtract the offset and then get the date.

    SELECT '1-1-2014 02:00:00'::timestamp + INTERVAL '1 hour' * extract(timezone_hour FROM '1-1-2014 00:02:00'::timestamp at time zone 'America/Los_Angeles');
    

    Adding the answer here, since I am sure this question might be something others would want to know.

    0 讨论(0)
提交回复
热议问题