Reputation: 439
I would like to extract the month of a given date in postgres e.g. '2020-02-03' --> 2.
I tried this with substr('2020-03-01',6,2)
it´s working, but I am getting the zero also.
date_part('month','2020-01-01')
as well as extract(month from date '2020-01-01')
[edit: syntax error]
is leading to an error.
How can I do it in the best way?
Upvotes: 0
Views: 2314
Reputation: 19613
Do not attempt to parse dates as strings. EXTRACT(MONTH
is exactly what you're looking for:
SELECT EXTRACT(MONTH FROM '2020-02-03'::DATE);
date_part
-----------
2
If your date is formatted as YYYYDDMM
try:
SELECT EXTRACT(MONTH FROM TO_DATE('2020-03-02','YYYY-DD-MM'));
date_part
-----------
2
Upvotes: 1