I need to convert my varchar to date.
My varchar looks like this:
event_date |
---|
2020-09-20 |
2021-07-21 |
2021-01-20 |
2020-10-08 |
Here is my attempted solution:
SELECT
TO_DATE(event_date,'YYYY-MM-DD')
FROM
database.schema.table
Here is the error I get:
Can't parse ' ' as date with format 'yyyy-mm-dd'
Can anybody help me out? Thanks!
You can use try_to_date(event_date,'YYYY-MM-DD'), it will return NULL (will not fail) if event_date can not be parsed, you can filter and check what exactly it contains:
SELECT
event_date as varchar_date,
TRY_TO_DATE(event_date,'YYYY-MM-DD') as parsed_date
FROM
database.schema.table
WHERE TRY_TO_DATE(event_date,'YYYY-MM-DD') IS NULL --filter and check
After checking which formats do you have, you can parse different formats using coalesce:
coalesce(TRY_TO_DATE(event_date,'YYYY-MM-DD'),
TRY_TO_DATE(event_date,'YYYYMMDD')
)
Answer was the trim() function for the extra spaces around my varchar. Thanks everyone!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.