Working with time zone information

Time Series Analysis in PostgreSQL

Jasmin Ludolf

Content Developer, DataCamp

Time zone data

  • TIMESTAMP : date and time information without time zone

    • Fine when using a single time zone
    • All times are in UTC
  • TIMESTAMPTZ : date and time with time zones

Illustration of four clock faces with different times.

Time Series Analysis in PostgreSQL

Time zone names

SELECT * FROM pg_timezone_names;
| name             |abbrev|utc_offset|is_dst|
|------------------|------|----------|------|
|Africa/Abidjan    |GMT   |  00:00:00|false |
|Africa/Accra      |GMT   |  00:00:00|false |
|Africa/Addis_Ababa|EAT   |   3:00:00|false |
...
  • is_dst : whether the location is observing daylight savings
Time Series Analysis in PostgreSQL

Show the time zone

SHOW TIMEZONE;
|TimeZone       |
|---------------|
|Europe/Brussels|
Time Series Analysis in PostgreSQL

Time zone data in tables

  • datetimes table has the following two fields:
    • datetime : TIMESTAMP
    • datetimetz : TIMESTAMPTZ
INSERT INTO datetimes (datetime, datetimetz)
VALUES('2023-01-03 12:00:00','2023-01-03 12:00:00');
|datetime           |datetimetz               |
|-------------------|-------------------------|
|2023-01-03 12:00:00|2023-01-03 12:00:00+01:00|
Time Series Analysis in PostgreSQL

Verify the data type

  • pg_typeof(field_name): check the data type of the field
SELECT
    pg_typeof(datetime) AS "type of(datetime)", 
    pg_typeof(datetimetz) AS "type of(datetimetz)"
FROM datetimes;
|type of(datetime)          |type of(datetimetz)     |
|---------------------------|------------------------|
|timestamp without time zone|timestamp with time zone|
Time Series Analysis in PostgreSQL

Using time zone information

INSERT INTO datetimes (datetime, datetimetz)
VALUES('2023-01-03 12:00:00+00','2023-01-03 12:00:00+00');
SELECT * FROM datetimes;
|datetime           |datetimetz               |
|-------------------|-------------------------|
|2023-01-03 12:00:00|2023-01-03 12:00:00+01:00|
|2023-01-03 12:00:00|2023-01-03 13:00:00+01:00|
Time Series Analysis in PostgreSQL

Adding time zone information

  • AT TIME ZONE: Add, change, or remove time zone information
    • Converting the type from TIMESTAMP to TIMESTAMPTZ and vice versa

Adding a time zone:

SELECT 
    TIMESTAMP '2020-12-31 23:59:59' AT TIME ZONE 'Europe/London' AS added;
|added                    |
|-------------------------|
|2021-01-01 00:59:59+01:00|

This query: interprets the timestamp, creates TIMESTAMPTZ, displays the default

Time Series Analysis in PostgreSQL

Changing and removing time zones

SELECT 
    '2020-12-31 23:59:59+00'::TIMESTAMPTZ AT TIME ZONE 'Europe/Paris' 
    AS shifted;
|shifted            |
|-------------------|
|2021-01-01 00:59:59|

This query: shifts the timestamp to the desired time zone, removes the time zone designation

Time Series Analysis in PostgreSQL

Let's practice!

Time Series Analysis in PostgreSQL

Preparing Video For Download...