Languages
[Edit]
EN

PostgreSQL - extract week from date/time value (ISO-8601)

0 points
Created by:
leila
255

In this article, we would like to show you how to extract week (ISO-8601) from DATE, TIMESTAMP TIME or INTERVAL in PostgreSQL.

Quick solution:

SELECT EXTRACT('week' FROM "column_name")
FROM "table_name";

 

PostgreSQL - extract week from timestamp/interval (ISO-8601)
Table used in the example - HeidiSQL

Note:

At the end of this article you can find database preparation SQL queries.

 

Practical example

In this example, we will only select weeks from each record in the event_datetime column.

Query:

SELECT EXTRACT('week' FROM "event_datetime") AS "week"
FROM "events";

Output:

PostgreSQL - extract week from timestamp/interval (ISO-8601)
Results - HeidiSQL

Database preparation

create_tables.sql file:

CREATE TABLE "events" (
	"id" SERIAL PRIMARY KEY,
	"event_timestamp" TIMESTAMP NOT NULL
);

insert_data.sql file:

INSERT INTO "events" 
	("event_timestamp")
VALUES
    ('2021-03-11 11:41:31'),
    ('2021-03-21 12:42:32'),
    ('2021-03-22 14:44:34'),
    ('2021-03-22 15:45:35'),
    ('2021-03-23 16:46:36'),
    ('2021-04-05 17:47:37'),
    ('2021-04-05 19:49:39'),
    ('2021-04-16 20:50:40'),
    ('2021-04-17 15:45:35'),
    ('2021-04-23 16:46:36'),
    ('2021-04-23 19:49:39'),
    ('2021-04-23 20:50:40');
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join