What this thread does
The problem
You store a time in Postgres and read it back hours earlier or later, or it differs between your local machine, the database client and production.
What the sources say
- PostgreSQL date/time types:
timestamp without time zonestores date and time without a zone; textual input of this type ignores any supplied zone. Conversion betweentimestamp without time zoneandtimestamptznormally uses the sessionTimeZone.timestamptzis stored as UTC and output in the current session zone. Our recommendation: usetimestamptzfor event instants andtimestamp without time zonefor a specific local date and time whose zone is handled separately.
What to do
1. Our example: in psql, check column types with \d tablename (replace tablename with your table name; one backslash). Writing now() into timestamp without time zone converts the instant to a wall-clock value using the session TimeZone. 2. Our recommendation: check the session that reads and the one that wrote. The SHOW reference documents reading a run-time setting; the date/time guide identifies the session setting as TimeZone. 3. Our recommendation: for instants, use timestamptz and send ISO strings with an offset. The date/time guide accepts ISO 8601 input with T, lists zulu as a military abbreviation for UTC, and lists z as its short form (also in ISO 8601). 4. Changing a column type can rewrite data: The ALTER TABLE reference documents changing a column type with a USING expression. The functions reference documents interpreting a timestamp without time zone value in a named zone. Our recommendation: for UTC wall-clock values in an existing timestamp without time zone column, design and test an explicit UTC conversion on a copy.
How to describe it to your agent
Timestamps in my Postgres app are shifted by hours. List the timestamp columns and their types, show SHOW timezone for the app connection, and explain which columns are instants and which are wall-clock. Write the migration with an explicit AT TIME ZONE and test it on a copy, never on production data.
Mistakes to check
- Converting with the wrong
AT TIME ZONEdirection. - Assuming a column stores the offset you sent.
- Daylight-saving edge cases for recurring local times.
Limits
Sources: date/time types, psql, SHOW, ALTER TABLE, and date/time functions.
Started from a post by @Larsenal, bignose, ddekany (Stack Overflow), packaged by the editor. Original post