How to get time in ISO format with UTC offset from PostgreSQL?

梦想的初衷 提交于 2019-12-01 12:26:47

问题


In python I can get time for different time zones in ISO format like this:

>>> import datetime
>>> import pytz
>>> datetime.datetime.now(tz=pytz.timezone('America/New_York')).isoformat()
'2019-03-15T04:01:23.919800-04:00'
>>> datetime.datetime.now(tz=pytz.timezone('Asia/Bangkok')).isoformat()
'2019-03-15T15:01:23.919800+07:00'

Now I need to get timestamps from postgresql in the same format. After some research the best I've come up with is this:

postgres=# set time zone 'America/New_York';
SET
postgres=# select to_json(now());
      to_json               
------------------------------------
 "2019-03-15T04:32:13.628323-04:00"

Is it possible to do that without changing the time zone of the database session? Something like:

postgres=# select to_json(now() at time zone 'America/New_York') NYC,
postgres-# to_json(now() at time zone 'Asia/Bangkok') Bangkok;
           nyc                |           bangkok         
------------------------------+------------------------------
 "2019-03-15T04:41:07.789954" | "2019-03-15T15:41:07.789954"

which is otherwise correct but missing the UTC offset.


回答1:


How about this?

SELECT current_timestamp AT TIME ZONE 'America/New_York'
       || replace('+' || to_char(current_timestamp AT TIME ZONE 'America/New_York'
                                 - current_timestamp AT TIME ZONE 'UTC',
                                'HH24:MMFM'),
                  '+-', '-');

             ?column?             
----------------------------------
 2019-03-15 05:43:38.901642-04:00
(1 row)


来源:https://stackoverflow.com/questions/55178954/how-to-get-time-in-iso-format-with-utc-offset-from-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!