DB
PostgreSQL timestamp vs timestamptz
땅부자몽구스
2021. 10. 14. 23:28
PostgreSQL에서 날짜와 시간을 표현하는 데이터 타입은 6가지가 있다.
하지만 그 중에서 날짜와 시간을 한번에 표현할 수 있는 데이터 타입은 timestamp와 timestamptz 2가지밖에 없다.
timestamptz는 이름에서 알 수 있듯이 timestamp에 추가로 타임존 정보를 가지고 있는 것처럼 보인다.
그러나 두 가지 데이터 타입의 길이는 모두 8 byte이다.
즉, timestamptz가 더 많은 데이터를 가지고 있지 "않다"는 뜻이다.
SELECT
pg_column_size('2000-01-01 00:00:00 +00:00'::timestamp) as "timestamp byte size",
pg_column_size('2000-01-01 00:00:00 +00:00'::timestamptz) as "timestamptz byte size";
+--------------------+-----------------------+
|timestamp byte size | timestamptz byte size |
+--------------------+-----------------------+
| 8 | 8 |
+--------------------+-----------------------+
timestamptz는 들어오는 데이터를 모두 UTC로 변환하여 저장한다.
즉, 데이터가 가진 타임존 offset을 인지하고 UTC로 변환하기 때문에 서로 다른 시간대의 데이터가 들어와도 올바르게 비교할 수 있게 된다.
SET TIME ZONE 'UTC';
SELECT
'2000-01-01 00:00:00 +05:00'::timestamp as "Timestamp without time zone",
'2000-01-01 00:00:00 +05:00'::timestamptz as "Timestamp with time zone";
+---------------------------+------------------------+
|Timestamp without time zone|Timestamp with time zone|
+---------------------------+------------------------+
| 2000-01-01 00:00:00 |1999-12-31 19:00:00+00 |
+---------------------------+------------------------+
따라서 timestamptz는 타임존 정보를 가진 타임스탬프가 아니라 데이터의 타임존 offset을 인지하는 데이터 타입이라고 이해하면 된다.
출처:
https://medium.com/building-the-system/how-to-store-dates-and-times-in-postgresql-269bda8d6403