2

I have a numeric data in a column 20170930, need help in converting it into Date in PostgreSQL , tried multiple ways but non seems to work

1
  • 1
    The correct solution to your problem is, to change the column's data type to DATE. Commented Aug 26, 2019 at 5:25

5 Answers 5

5

You can convert to a string and then to a date:

select column::text::date

You can also express this using explicit cast() syntax:

select cast(cast(20170930 as text) as date)
Sign up to request clarification or add additional context in comments.

2 Comments

but when I use :: in Spring entity manager, it gives me error as syntax error at : or close to :
@abhi . . . :: is quite valid Postgres syntax and that is what your question is tagged. I don't know why a particular "framework" would not allow such code. But you can easily replace it with the equivalent cast().
0

Use one of the following :

SELECT cast(yourcol::varchar as date ) as dt1, yourcol::varchar::date as dt2

where dt1 and dt2 values of type date, and yourcol is a numeric value such as 20170930

Demo

4 Comments

I get this error ERROR: cannot cast type numeric to date Position: 18
excuse me, you're right. I just noticed that your value is of type numeric and needed to be converted to varchar(of type text) first @abhi , since you already told that "I have a numeric data in a column 20170930".
now I am getting [22007] ERROR: invalid input syntax for type date: "20170930.000000"
I've added the demo. I didn't understand what could be the problem @abhi
0

The best thing is to change column datatype into Date type,

  ALTER TABLE table_name
    ADD column_name Date;

enter image description here As shown above, PostgreSQL supports a full set of SQL date and time types, as shown in the table below. Dates are counted according to the Gregorian calendar. Here, all the types have a resolution of 1 microsecond / 14 digits except date type, whose resolution is day.

Comments

0

Please try below query

SELECT to_date(column::varchar,'YYYYMMDD') 

Comments

0

For anybody who fell into my pitfall I tried this but my numeric was like a 'seconds past 01-01-1970 format' rather than YYYYMMDD

This worked

SELECT to_timestamp(yourcol) as numeric_column_now_date
from yourtable

see here https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.