【发布时间】:2021-04-12 22:38:48
【问题描述】:
为什么在写入和读取具有日期时间列的行时会得到不同的时区?
我有下一张桌子Tests:
class Test(Base):
__tablename__ = 'tests'
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=True)
test_datetime = Column(DateTime(timezone=True), nullable=False, default=datetime.utcnow())
def __init__(self, test_datetime):
self.test_datetime = test_datetime
def __repr__(self):
return f'<Test(id={self.id}, test_datetime={self.test_datetime})'
我决定将感知的日期时间以 UTC 格式存储在数据库和测试表中。 我正在向表中添加新行。测试对象具有感知日期时间。
session.add(Test(datetime.utcnow().replace(tzinfo=pytz.UTC)))
session.commit()
session.close()
psql 选择命令输出:
database_name=# select * from tests; id | test_datetime
--------------------------------------+-----------------------------
751bcef0-2ef4-4c0f-960c-a40ca2b8ec94 | 2021-04-12 14:46:30.8957+03
(1 row)
database_name=# SHOW timezone ;
TimeZone
---------------
Europe/Moscow
(1 row)
database_name=# \d tests
Table "public.tests"
Column | Type | Collation | Nullable | Default
---------------+--------------------------+-----------+----------+---------
id | uuid | | not null |
test_datetime | timestamp with time zone | | not null |
Indexes:
"tests_pkey" PRIMARY KEY, btree (id)
我们看到datatime列被错误地写入数据库(时区偏移+3小时放置+0)。
按预期从数据库中读取数据,我得到了不同的时区 (+3h)
query = session.query(Test)
for test in query.order_by(Test.test_datetime.asc()).all():
print(test.test_datetime, test.test_datetime.tzinfo)
Python 输出:
2021-04-12 14:46:30.895700+03:00 psycopg2.tz.FixedOffsetTimezone(offset=180, name=None)
我的数据库有一个时区:“欧洲/莫斯科”。 有一个假设:有可能在写入数据库时,日期时间被保存为 naive。并且 test_datetime 列中的所有对象都从数据库中获取时区(偏移量)。 但我不确定它是否可以这样工作。
【问题讨论】:
-
在 psql 中,当您执行
\d tests时,它是否将 test_datetime 列显示为“带时区的时间戳”? -
是的“带时区的时间戳”。为帖子添加了 \d 输出。
标签: python postgresql sqlalchemy python-datetime