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 Respuestas
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
EXPERTO
respondido hace un año
profile picture
EXPERTO
iwasa
revisado hace un año
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
EXPERTO
respondido hace un año
profile picture
EXPERTO
iwasa
revisado hace un año

No has iniciado sesión. Iniciar sesión para publicar una respuesta.

Una buena respuesta responde claramente a la pregunta, proporciona comentarios constructivos y fomenta el crecimiento profesional en la persona que hace la pregunta.

Pautas para responder preguntas