Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract week number from date postgres

I would like to extract the week number as:

2015-52 

from a date formatted as:

2015-12-27 

How can I perform this in postgres?

my weeks are calculated from monday to sunday.

like image 949
chopin_is_the_best Avatar asked Dec 02 '15 18:12

chopin_is_the_best


People also ask

How do I get the current week number in PostgreSQL?

Use the DATE_PART() function to retrieve the week number from a date in a PostgreSQL database. This function takes two arguments. The first argument is the date part to retrieve; we use 'week', which returns the week number (e.g. “1” for the first week in January, the first week of the year).

What is epoch in Postgres?

Posted on 28th August 2022. YES, you can convert EPOCH to Timestamp by merely switching to the present Timestamp in PostgreSQL DBMS. EPOCH time is nothing but the number of seconds from 00:00:00 UTC on 1 January 1970. Till date, without adding the extra leap year days, this is considered.

What is the number of this week?

week-number.net The current Week Number is WN 34.

How do I write a cast in PostgreSQL?

PostgreSQL supports a CAST operator that is used to convert a value of one type to another. Syntax: CAST ( expression AS target_type ); Let's analyze the above syntax: First, specify an expression that can be a constant, a table column, an expression that evaluates to a value.


2 Answers

To get the year and the week in a single character value, use to_char()

select to_char(current_date, 'IYYY-IW'); 

IW returns the year and the week number as defined in the ISO standard and IYYY returns the corresponding year (which might be the previous year).

If you need the year and the week number as numbers, use extract

select extract('isoyear' from current_date) as year,         extract('week' from current_date) as week; 
like image 156
a_horse_with_no_name Avatar answered Sep 28 '22 15:09

a_horse_with_no_name


I have done like this

extract(week from cast(current_date as date)) extract(year from cast(current_date as date)) 
like image 39
Praveenkumar Beedanal Avatar answered Sep 28 '22 14:09

Praveenkumar Beedanal