【问题标题】:How to insert record of python datetime and timezone info into oracle timestamp with zone column using sqlachemy如何使用 sqlachemy 将 python 日期时间和时区信息的记录插入带有区域列的 Oracle 时间戳
【发布时间】:2021-04-19 06:20:39
【问题描述】:

我有现有的 oracle 数据库,其中包含表 'STUDENT'。下面是table的字段和数据类型:

ID -- NUMBER
NAME -- VARCHAR(100)
CREATED_DATE -- TIMESTAMP(6) WITH TIME ZONE DEFAULT current_timestamp allow null
MODIFIED_DATE -- TIMESTAMP(6) WITH TIME ZONE DEFAULT current_timestamp allow null

我可以使用 sqlalchemy 连接 oracle 数据库,如下所述:

from sqlalchemy.sql import select
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.ext.automap import automap_base
DIALECT = 'oracle'
SQL_DRIVER = 'cx_oracle'
USERNAME = '******'
PASSWORD = '******'
HOST = '*******'
PORT = 1521
SERVICE = '*****'
ENGINE_PATH_WIN_AUTH = DIALECT + '+' + SQL_DRIVER + '://' + USERNAME + ':' + PASSWORD +'@' + HOST + ':' + str(PORT) + '/?service_name=' + SERVICE
engine = create_engine(ENGINE_PATH_WIN_AUTH, max_identifier_length=128, echo=True, connect_args={"encoding": "utf-8"})

Base = automap_base()
Base.prepare(self.engine, reflect=True)

我可以使用以下代码将 oracle 数据库中的表映射到 sqlalchemy 对象:

Base = automap_base()
Base.prepare(self.engine, reflect=True)
STUDENT = Base.classes.student
db_session = Session(engine)

在上面的代码之后,我写了一个代码,使用 sqlalchemy 将数据插入到表中。

from datetime import datetime
from pytz import timezone
data = [(1, 'stud1'), (2,'stud2'), (3, 'stud3')]
for d in data:
    date_created = datetime.now(timezone('Europe/London'))
    date_modified = datetime.now(timezone('Europe/London'))
    
    stud_record = STUDENT(id=d[0], name=d[1], created_date=date_created, modified_date = date_modified)
    db_session.add(stud_record)
db_session.commit()

执行代码后,我可以将记录插入表中,但我可以在created_datemodified_date 列中看到日期时间和时间戳值。例如 (13-JAN-21 04.23.41.343000000 +00:00)

我还想要该列中的时区值,例如。例如 13-JAN-21 04.23.41.343000000 EUROPE/LONDON

请建议我在代码中做错了什么,如何使用sqlalchemy? 将 python 日期时间和时间戳值插入到 oracle 表列(TIMESTAMP(6) WITH TIME ZONE)中?

【问题讨论】:

  • 你从select TO_CHAR(created_date, 'YYYY-MM-DD HH24:MI:SS TZR')得到什么?
  • @WernfriedDomscheit 我收到了这个回复2021-01-13 08:40:41 +00
  • 你确定吗?时区+00不存在,见SELECT * FROM V$TIMEZONE_NAMES WHERE tzname = '+00'
  • 是的,我从专栏中得到了相同的回复。

标签: python oracle sqlalchemy flask-sqlalchemy python-datetime


【解决方案1】:

我找到了这个:Mastering Oracle+Python, Part 2: Working with Times and Dates,上面写着:

在日期时间上下文中需要记住的关于 cx_Oracle 4.3 的重要事项:

  • 不支持 INTERVAL 和 TIMESTAMP WITH (LOCAL) TIME ZONE

我认为解决方案是这样的:

如果客户端发送的时间戳没有时区信息(python 似乎就是这种情况),那么 Oracle 会默认时区为 SESSIONTIMEZONE

连接到 Oracle 后,在 python 中运行ALTER SESSION SET TIME_ZONE = 'Europe/London'。或者设置环境变量ORA_SDTZ=Europe/London

【讨论】:

  • 是的,我看到了,但它是 2007 年相当古老​​的线程以及信息。谢谢,我会检查环境变量。我也没有使用cx_Oracle
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-30
  • 2019-01-28
  • 1970-01-01
  • 2018-02-08
  • 2018-12-30
  • 2020-11-27
相关资源
最近更新 更多