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 Risposte
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
ESPERTO
con risposta un anno fa
profile picture
ESPERTO
iwasa
verificato un anno fa
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
ESPERTO
con risposta un anno fa
profile picture
ESPERTO
iwasa
verificato un anno fa

Accesso non effettuato. Accedi per postare una risposta.

Una buona risposta soddisfa chiaramente la domanda, fornisce un feedback costruttivo e incoraggia la crescita professionale del richiedente.

Linee guida per rispondere alle domande