首页 > 解决方案 > 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 对象时区?

标签: pythonpython-3.xpostgresqldatetimepsycopg2

解决方案


我以这种方式解决了这个问题:我在类 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


推荐阅读