How to Extract Year from DATE in POSTGRESQL

PostgresqlDateDatetime

Postgresql Problem Overview


Date is in 'YYYY-MM-DD' text format, now I need to extract the year part which must be in numeric. I need this conversion to be done in single step, Since I need to use in other application where i cannot create new variable.

TO_DATE(t0.AESTDTC,'YYYY-MM-DD'),'YYYY-MM-DD' with this i was able to convert to date but Now i need to Extract the year from this date in single step? can any one help me?

Postgresql Solutions


Solution 1 - Postgresql

Try

select date_part('year', your_column) from your_table;

or

select extract(year from your_column) from your_table;

Solution 2 - Postgresql

This line solved my same problem in postgresql:

SELECT DATE_PART('year', column_name::date) from tableName;

If you want month, then simply replacing year with month solves that as well and likewise.

Solution 3 - Postgresql

answer is;

select date_part('year', timestamp '2001-02-16 20:38:40') as year,
       date_part('month', timestamp '2001-02-16 20:38:40') as month,
       date_part('day', timestamp '2001-02-16 20:38:40') as day,
       date_part('hour', timestamp '2001-02-16 20:38:40') as hour,
       date_part('minute', timestamp '2001-02-16 20:38:40') as minute

Solution 4 - Postgresql

Choose one from, where :my_date is a string input parameter of yyyy-MM-dd format:

SELECT EXTRACT(YEAR FROM CAST(:my_date AS DATE));

or

SELECT DATE_PART('year', CAST(:my_date AS DATE));

Better use CAST than :: as there may be conflicts with input parameters.

Solution 5 - Postgresql

You may try to_char(now()::date, 'yyyy')
If text, you've to cast your text to date to_char('2018-01-01'::date, 'yyyy')

See the PostgreSQL Documentation Data Type Formatting Functions

Solution 6 - Postgresql

you can also use just like this in newer version of sql,

select year('2001-02-16 20:38:40') as year,
month('2001-02-16 20:38:40') as month,
day('2001-02-16 20:38:40') as day,
hour('2001-02-16 20:38:40') as hour,
minute('2001-02-16 20:38:40') as minute

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKarthiView Question on Stackoverflow
Solution 1 - PostgresqlflaviodesousaView Answer on Stackoverflow
Solution 2 - PostgresqlhillsonghimireView Answer on Stackoverflow
Solution 3 - PostgresqlHasan BINBOGAView Answer on Stackoverflow
Solution 4 - PostgresqlZonView Answer on Stackoverflow
Solution 5 - PostgresqlRajib ChyView Answer on Stackoverflow
Solution 6 - PostgresqlSR_MehtaView Answer on Stackoverflow