python psycopg2选择时区的current_timestamp问题

标签 python python-3.x postgresql datetime psycopg2

我正在调用一个简单的选择来获取带有 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 中的当前时间戳? 如果不是,我如何转换日期时间对象时区?

最佳答案

我是这样解决这个问题的: 我在类 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 psycopg2选择时区的current_timestamp问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65709643/

相关文章:

python - 使用 Miniconda 创建新的 Python 安装

python - 如何使用作为环境变量生成的 PyNaCl key

postgresql - 解决用户 postgres 启动进程分配 2405% CPU 的问题

sql - Postgresql 连接列并在列为 NULL 或为空字符串时跳过列

python - 从同级目录导入 Python 类

python - 创建包含多个 HTTP 请求的 mime/multipart 请求

python - 在 python 中从二进制数据保存 JPG 图像时出现问题

python-3.x - Numpy 在 Cython 中,没有改进

python - 在 python 中显示原始图像像素而不是掩码

sql - 从每行中排除最大元素