【问题标题】:Compare a date and a timezone to a timestamptz in Postgresql将日期和时区与 Postgresql 中的时间戳进行比较
【发布时间】:2017-10-09 21:52:34
【问题描述】:

我有一个表,其中包含一个 date 列和一个包含时区的 varchar 列。我想编写一个查询,选择时区午夜日期在给定timestamp with time zone 之前的所有行。

例如,给定

CREATE TABLE scheduled_tasks (
  id serial primary key,
  run_date date not null,
  customer_timezone varchar not null
 );

INSERT INTO scheduled_tasks(run_date, customer_timezone) VALUES 
  ('2017-10-15', 'America/Los_Angeles'),
  ('2017-10-15', 'America/New_York'),
  ('2017-10-15', 'Asia/Tokyo');

如果我希望每个任务在其关联时区的午夜之后运行,我将如何编写查询以查找应在 2017-10-15T06:00:00Z 运行的所有 scheduled_tasks? (所以我想要东京和纽约的任务,而不是洛杉矶的任务,因为2017-10-15T06:00:00Z 是洛杉矶 14 日晚上 11:00。)

我看到了make_timestamptz 函数,但我最好的选择真的是:

SELECT *
FROM scheduled_tasks
WHERE make_timestamptz(
  EXTRACT (YEAR from run_date)::int,
  EXTRACT (MONTH from run_date)::int,
  EXTRACT (DAY from run_date)::int,
  0,
  0,
  0.0,
  customer_timezone) < '2017-10-15T06:00:00';

SqlFiddle:http://sqlfiddle.com/#!17/a8e38/4/0

【问题讨论】:

    标签: postgresql date datetime


    【解决方案1】:
    SELECT run_date::timestamp AT TIME ZONE customer_timezone < '2017-10-15T06:00:00Z'::timestamptz
    FROM scheduled_tasks;
    

    在此查询中,我首先创建特定时区的时间,然后创建 UTC 的预期运行时间,然后进行比较。

    【讨论】:

    • 您好,我正在尝试您的答案,但是当我在 timestamp without time zone 列上尝试时,像这样:created at time zone '-06:00' 它会从原来的时间中减去 12 小时,有没有办法让它不影响时间和日期值 (which I understand PG always stores in UTC),只需更改时区。我正在尝试比较日期,并且我正在尝试首先让它们进入相同的 tz。谢谢
    • @Scaramouche at time zone 构造将timestamp 转换为timestamptz,例如您的原始时间戳已经在在那个时区。如果您原来的 timestamp 是 UTC,那么您应该首先将 UTC 附加到它,然后将其转换为所需的区域:(('2020-01-01T00:00:00'::timestamp) at time zone 'UTC') at time zone 'Europe/Oslo'
    猜你喜欢
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2020-04-22
    • 2017-05-04
    相关资源
    最近更新 更多