SqlAlchemy converting UTC DateTime to local time before saving

前端 未结 1 780
后悔当初
后悔当初 2020-12-25 09:23

I have the following situation: - Postgres backend with a field

timestamp without time zone
  • Right before saving the datetime value,
相关标签:
1条回答
  • 2020-12-25 09:47

    What I suspect is happening is that you are storing aware datetimes correctly, but are not reading it back with a time zone because the column is WITHOUT TIME ZONE. Each PostgreSQL connection has an associated time zone that defaults to the system's time zone, so when you retrieve a particular TIMESTAMP it gets returned as a naïve datetime in the system's time zone. For this reason, I always recommend storing TIMESTAMP WITH TIME ZONE instead.

    If you want to change the time zone of the connection in SQLAlchemy to UTC, do the following when you create the engine:

    engine = create_engine("...", connect_args={"options": "-c timezone=utc"})
    

    This should make you read the value back as a naïve datetime in UTC.

    EDIT: @Peter The documentation does not make it obvious how to do this; I had to read several different docs and connect the dots:

    1. the SQLAlchemy documentation about connect_args that allows you to pass arguments directly to the DBAPI connect()
    2. the psycopg2 documentation on connect, which tells you about the extra parameters you can pass to libpq
    3. the libpq documentation on the options parameter that allows you to pass command-line options when connecting with libpq
    4. the the PostgreSQL documentation about the -c command-line switch that allows you to modify config settings
    5. finally, the PostgreSQL client documentation about the timezone client setting that you can set
    0 讨论(0)
提交回复
热议问题