INVALID_CAST_ARGUMENT: Value cannot be cast to date: None

0

I have a string type for date and in that column, it has the word 'None'

My query for casting the date is below - getting only the Month and Year on it,

date_format(cast(c.enddate as date), '%M') as "Month", date_format(cast(c.enddate as date), '%Y') as "Year"

ERROR prompted INVALID_CAST_ARGUMENT: Value cannot be cast to date: None-

Can somebody help me with this problem, so that I can still get the Month and Year only?

Thank you in advance!

2 Answers
1

Hi,

the issue is that you are trying to cast the word ‘None’ to a date, which of course will throw an error.

You should add a clause which exclude this value, like where enddate != (is not) ‘None’ or similar, not knowing the context of the query (database, sql, or something else).

Hope it helps and if it does I would appreciate answer to be accepted so that community can benefit for clarity, thanks ;)

profile picture
EXPERT
answered a year ago
profile picture
EXPERT
iwasa
reviewed a year ago
0

You can use a CASE statement to handle the 'None' values before casting the date. In this example, I'll replace 'None' with a NULL value, then proceed with your original query.

date_format(
    cast(
        CASE 
            WHEN c.enddate = 'None' THEN NULL 
            ELSE c.enddate 
        END as date
    ), 
    '%M'
) as "Month", 
date_format(
    cast(
        CASE 
            WHEN c.enddate = 'None' THEN NULL 
            ELSE c.enddate 
        END as date
    ), 
    '%Y'
) as "Year"

This query first checks if c.enddate is 'None', and if so, it replaces it with a NULL value. Then it proceeds with the original cast and date_format functions to extract the Month and Year.

profile picture
EXPERT
answered a year ago
profile picture
EXPERT
iwasa
reviewed a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions