【问题标题】:PostgreSQL: Convert MongoDB date format to timestamptzPostgreSQL:将 MongoDB 日期格式转换为 timestamptz
【发布时间】:2017-10-01 07:33:23
【问题描述】:

我参考了 psql documentation 并提出了这个查询。

SELECT to_timestamp('Tue Aug 30 2016 04:07:13 GMT+0530 (IST)', 'Dy MON DD YYYY HH24:MI:SS');

这个日期时间字符串 Tue Aug 30 2016 04:07:13 GMT+0530 (IST) 是我从 MongoDB printjson(createdAt) 得到的。

上面的 postresql 似乎不适用于所有偏移量。

我试过了

select to_timestamp('Tue Aug 30 2016 04:07:13 GMT+0530 (IST)', 'Dy MON DD YYYY HH24:MI:SS "GMT"OF "(IST)"');

但我收到此错误``错误:to_date` 不支持“TZ”/“tz”/“OF”格式模式。

如何将此字符串Tue Aug 30 2016 04:07:13 GMT+0530 (IST)转换为psql timestamptz格式?

【问题讨论】:

    标签: sql postgresql timestamp-with-timezone


    【解决方案1】:

    它看起来是一个丑陋的轮子,并且对于每个无法识别的偏移量都需要这样的replace,但它可以工作。对于您的示例,将'GMT+0530 (IST)' 替换为'GMT+05:30',它将被提取:

    t=# select replace('Tue Aug 30 2016 04:07:13 GMT+0530 (IST)','GMT+0530 (IST)','GMT+05:30')::timestamptz;
            replace
    ------------------------
     2016-08-30 09:37:13+00
    (1 row)
    t=# select replace('Tue Aug 30 2016 14:07:13 GMT+0530 (IST)','GMT+0530 (IST)','GMT+05:30')::timestamptz;
            replace
    ------------------------
     2016-08-30 19:37:13+00
    (1 row)
    

    更新:取决于您的时区,结果可能会令人困惑:

    t=# set timezone TO 'GMT-5:30';                                          SET
    t=# select replace('Tue Aug 30 2016 14:07:13 GMT+0530 (IST)','GMT+0530 (IST)','GMT+05:30')::timestamptz;
              replace
    ---------------------------
     2016-08-31 01:07:13+05:30
    (1 row)
    

    要检查是否正确,请使用:

    t=# select replace('Tue Aug 30 2016 14:07:13 GMT+0530 (IST)','GMT+0530 (IST)','GMT+05:30')::timestamptz at time zone 'UTC';
          timezone
    ---------------------
     2016-08-30 19:37:13
    (1 row)
    

    【讨论】:

    • 它是否处理 24 小时格式?我认为查询正在将我的 24 小时时钟转换为 12 小时!
    • 感谢 Vao。当我尝试时,它没有正确转换。它也与系统时钟设置有关吗?我会用几个例子来说服自己。
    • 发布示例?.. 在您看到确切的错误之前很难判断
    • 用检查方式更新了答案。您还可以为您的客户设置时区以避免双重转换混乱
    • 问@vitaly-t - 他在 SO 上非常活跃
    猜你喜欢
    • 2023-03-09
    • 2018-02-22
    • 1970-01-01
    • 2016-06-12
    • 2011-05-16
    • 2020-08-04
    • 2021-06-18
    • 2018-02-12
    • 1970-01-01
    相关资源
    最近更新 更多