python - python psycopg2选择时区的current_timestamp问题
问题描述
我正在调用一个简单的选择来获取带有 psycopg2 的时区的当前时间戳,它正在检索 UTC 时间而不是我的本地时间 (-3)。
datetime.datetime(2021, 1, 13, 20, 49, 47 , 931834, tzinfo=psycopg2.tz.FixedOffsetTimezone( offset=0, name=None))
在 postgresql 我正在做:
select current_timestamp
这检索(阿根廷时间-3):
2021-01-13 17:39:57
所以这是正确的,但是在 Python 中:
class DatabaseUtils():
def __init__(self):
self.dsn = "dbname=my_database user=postgres host=127.0.0.1"
self.conn, self.cur = self.connect_db()
self.database_name = "my_table"
def connect_db(self):
"""
:param DSN: data source name. ex: "dbname=sigbase user=postgres"
:return: connection, cursor < If successful
"""
try:
# Connect to the database
conn = psycopg2.connect(self.dsn)
# Default encoding is UTF8
conn.set_client_encoding('UTF8')
cur = conn.cursor()
except:
logger.error(f'Could not connect to database {self.dsn}')
conn, cur = None, None
return conn, cur
def myselect(self):
query = "select current_timestamp ;"
self.cur.execute(query)
records = self.cur.fetchall()
logger.debug(f"Selected records {records}")
选择方法检索:
Selected records [(datetime.datetime(2021, 1, 13, 20, 49, 47, 931834, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)),)]
所以 datetime 对象的偏移量为 0,即 UTC。 是否可以使用正确的时区检索 psycopg2 中的当前时间戳?如果没有,我该如何转换 datetime 对象时区?
解决方案
我以这种方式解决了这个问题:我在类 init 中添加了一个方法来设置时区。通过这种方式,SELECT 语句给出了适当的时间。
def set_timezone(self):
# Get current time zone.
timezone = datetime.datetime.now(datetime.timezone.utc).astimezone().tzname()
# Set timezone.
self.cur.execute(f"SET TIME ZONE {timezone};")
用python记录的结果是:
Selected records [(datetime.datetime(2021, 1, 14, 14, 21, 18, 455322, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-180, name=None)),)]
这是正确的(现在是阿根廷时间)。
额外信息:我基于 psycopg 文档,在示例中是在查询之前先告诉时区。我认为这个库中的 select current_time 默认情况下在 UTC 中工作。
资料来源:https ://www.psycopg.org/docs/usage.html#time-zones-handling
推荐阅读
- python - 将 websocket 价格流保存到本地数据库
- kotlin - 浓缩咖啡pressKey(KeyEvent.KEYCODE_CAPS_LOCK)不工作
- ios - 使用 Swift 5.3.2 编译的模块不能被 Swift 5.4.2 编译器(芯片 M1)导入
- jquery - Jquery 3.6.0-> 1.Ajax 成功响应仅在 IE 中未定义,2).data 在开发工具的网络中显示,它在 fire fox 和 chrome 中工作正常
- yarnpkg - 将纱线工作区作为依赖添加到其他工作区
- c - 无法打印出名称消息 C 套接字
- javascript - 按钮按下不激活功能
- javascript - 使用 Puppeteer 生成 PDF 时无法隐藏 Fusion Charts 图形水印
- json - 一页上有多个放大器列表
- postgresql - 插入分区表postgresql