从 cx_oracle 游标检索时区感知日期时间对象的正确方法是什么?
cx_oracle 返回 TIMESTAMP
或 TIMESTAMP WITH TIME ZONE
类型列的 datetime
实例,但这些 datetime 实例不支持时区。
例如:
SELECT column_name, data_type FROM ALL_TAB_COLUMNS WHERE table_name = 'mytable';
column_name data_type
----------- ---------------------------
MYCOL TIMESTAMP(6) WITH TIME ZONE
如您所见,MYCOL 是一个可识别时区的 TIMESTAMP。我希望以下内容会返回一个包含 tzinfo 数据的 Python 日期时间对象。但是:
>>> cxoracle_cursor.execute("select mycol from mytable")
>>> row = cx_oracle_cursor.fetchone()
>>> row['mycol']
datetime.datetime(2011, 6, 15, 8, 30)
该日期时间对象不了解时区,因此我无法在我的应用程序中可靠地使用此日期。
将此列检索为时区感知的日期时间对象的最佳方法是什么?
cx_oracle returns datetime
instances for columns of the TIMESTAMP
or TIMESTAMP WITH TIME ZONE
types, but these datetime instances are not timezone aware.
For example:
SELECT column_name, data_type FROM ALL_TAB_COLUMNS WHERE table_name = 'mytable';
column_name data_type
----------- ---------------------------
MYCOL TIMESTAMP(6) WITH TIME ZONE
As you can see, MYCOL is a TIMESTAMP which is timezone aware. I would expect that the following would return a Python datetime object that contains tzinfo data. However:
>>> cxoracle_cursor.execute("select mycol from mytable")
>>> row = cx_oracle_cursor.fetchone()
>>> row['mycol']
datetime.datetime(2011, 6, 15, 8, 30)
That datetime object isn't timezone aware, so I can't reliable use this date in my application.
What is the best approach to retrieving this column as a datetime object that is timezone aware?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里我看到以下内容:对于 TIMESTAMP WITH TIME ZONE 数据,日期时间值始终采用 UTC,因此不需要转换。
因此,如果您获取
datetime
对象时区不知道,我知道它是UTC。所以你可以这样做:或者尝试使用函数
SYS_EXTRACT_UTC
(从具有时区偏移的日期时间中提取UTC),然后使用pytz.utc.localize
>。Here I see the following: For TIMESTAMP WITH TIME ZONE data, the datetime value is always in UTC, so no conversion is necessary.
So if you get the
datetime
object timezone unaware, I understand it is in UTC. So you can do:Or try the function
SYS_EXTRACT_UTC
(Extracts the UTC from a datetime with time zone offset) and then withpytz.utc.localize
.