I have the following situation: - Postgres backend with a field
timestamp without time zone
So in the database the date stored is no longer 6AM .. but 9AM - it's converted in my local timezone.
I don't understand what's happening. Why is the saved date converted to local ?
Thanks.
Edit
So after @univerio's reply I tried something: I removed the tzinfo from the date time by doing
.replace(tzinfo = None)
And now the date is saved correctly - it doesn't adjust it to the local time. I don't quite understand why so I'll leave the question open for now in case someone has an explanation.
Thanks.
What I suspect is happening is that you are storing aware datetime
s 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:
connect_args
that allows you to pass arguments directly to the DBAPI connect()
connect
, which tells you about the extra parameters you can pass to libpqoptions
parameter that allows you to pass command-line options when connecting with libpq-c
command-line switch that allows you to modify config settingstimezone
client setting that you can setIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With