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!

已提問 1 年前檢視次數 2028 次
2 個答案
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
專家
已回答 1 年前
profile picture
專家
iwasa
已審閱 1 年前
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
專家
已回答 1 年前
profile picture
專家
iwasa
已審閱 1 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南