0

I am unable to pass a date string in spark sql

When I run this

spark.sql(""" SELECT cast ('2021-04-12' as date) """)
> DataFrame[CAST(2021-04-12 AS DATE): date]

However I get error when I want to pass the date string as variable

 date_str = '2021-04-12'
 spark.sql(""" SELECT cast ({} as date) """.format(date_str))

 > AnalysisException: cannot resolve 'CAST(((2021 - 4) - 12) AS DATE)' 
 > due to data type mismatch: cannot cast int to date; line 1 pos 7;

I am not sure, how to pass that variable.

2 Answers 2

2

you can just add single quotes to the query and it should work for you

spark.sql(""" SELECT cast ('{}' as date) """.format(date_str))
Sign up to request clarification or add additional context in comments.

Comments

0

One more way to do that would be using fstring:

spark.sql(f""" SELECT cast ('{date_str}' as date) """)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.