Time Series Analysis in PostgreSQL
Jasmin Ludolf
Content Developer, DataCamp
TIMESTAMP
: date and time information without time zone
TIMESTAMPTZ
: date and time with time zones
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 savingsSHOW TIMEZONE;
|TimeZone |
|---------------|
|Europe/Brussels|
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|
pg_typeof(field_name)
: check the data type of the fieldSELECT
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|
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|
AT TIME ZONE
: Add, change, or remove time zone informationTIMESTAMP
to TIMESTAMPTZ
and vice versaAdding 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
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