Time Series Analysis in PostgreSQL
Jasmin Ludolf
Content Developer, DataCamp
AGE()
: subtracts the second argument from the first argument or the current dateAGE(timestamp, timestamp)
or AGE(timestamp)
SELECT
AGE('2018-01-02','2017-01-01') AS "2017",
AGE('2021-01-05','2020-01-01') AS "2020";
|2017 |2020 |
|------------|-------------|
|1 year 1 day|1 year 4 days|
SELECT
AGE('2017-12-31','2017-01-01') AS "2017",
AGE('2018-12-31','2018-01-01') AS "2018",
AGE('2019-12-31','2019-01-01') AS "2019",
AGE('2020-12-31','2020-01-01') AS "2020";
|2017 |2018 |2019 |2020 |
|---------------|---------------|---------------|---------------|
|11 mons 30 days|11 mons 30 days|11 mons 30 days|11 mons 30 days|
SELECT
'2018-01-01'::DATE - '2017-01-01'::DATE AS "2017",
'2019-01-01'::DATE - '2018-01-01'::DATE AS "2018",
'2020-01-01'::DATE - '2019-01-01'::DATE AS "2019",
'2021-01-01'::DATE - '2020-01-01'::DATE AS "2020";
|2017|2018|2019|2020|
|----|----|----|----|
| 365| 365| 365| 366|
-
: subtract operatorINTERVAL
data typeINTERVAL
allows us to store and manipulate a period of timeSELECT
'2021-01-01 00:03:00'::TIMESTAMP - '2021-01-01 00:01:30'::TIMESTAMP
AS interval;
|interval|
|--------|
|00:01:30|
WITH line_324 AS (
SELECT station, arrival_time
FROM train_schedule
WHERE train_id=324 )
SELECT hillsdale.arrival_time - millbrae.arrival_time AS diff
FROM line_324 AS millbrae, line_324 AS hillsdale
WHERE millbrae.station='Millbrae'
AND hillsdale.station='Hillsdale';
WITH line_324 AS (
SELECT station, arrival_time
FROM train_schedule
WHERE train_id=324 )
SELECT hillsdale.arrival_time - millbrae.arrival_time AS diff
FROM line_324 AS millbrae, line_324 AS hillsdale
WHERE millbrae.station='Millbrae'
AND hillsdale.station='Hillsdale';
|diff |
|--------|
|00:08:00|
SELECT
'2020-02-01'::DATE - INTERVAL '1 month' AS "1 month sooner";
|1 month sooner |
|-------------------|
|2020-01-01 00:00:00|
EXTRACT(epoch FROM start_time - end_time)
SELECT EXTRACT(epoch FROM ('2021-01-01 00:03:00'::TIMESTAMP - '2021-01-01 00:01:30'::TIMESTAMP))
AS seconds;
|seconds|
|-------|
| 90.0|
SELECT (EXTRACT(epoch FROM
('2021-01-01 00:01:00'::TIMESTAMP - '2020-12-31 23:59:30'::TIMESTAMP)))
/ 60 AS minutes;
|minutes|
|-------|
| 1.5|
SELECT '2019-02-01'::DATE + INTERVAL '28 days' AS "28 days later";
|28 days later |
|-------------------|
|2019-03-01 00:00:00|
SELECT '2020-02-01'::DATE + INTERVAL '28 days' AS "28 days later";
|28 days later |
|-------------------|
|2020-02-29 00:00:00|
SELECT '2019-02-01'::DATE + INTERVAL '1 month' AS "1 month later";
|1 month later |
|-------------------|
|2019-03-01 00:00:00|
SELECT '2020-02-01'::DATE + INTERVAL '1 month' AS "1 month later";
|1 month later |
|-------------------|
|2020-03-01 00:00:00|
Time Series Analysis in PostgreSQL