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 Antworten
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
EXPERTE
beantwortet vor einem Jahr
profile picture
EXPERTE
iwasa
überprüft vor einem Jahr
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
EXPERTE
beantwortet vor einem Jahr
profile picture
EXPERTE
iwasa
überprüft vor einem Jahr

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen