0

I have a spark app, that need to convert from string to timestamp below is my code.

val df = sc.parallelize(Seq("09/18/2017","")).toDF("sDate")
+----------+
|     sDate|
+----------+
|09/18/2017|
|          |
+----------+
val ts = unix_timestamp($"sDate","MM/dd/yyyy").cast("timestamp")
df.withColumn("ts", ts).show()
+----------+--------------------+
|     sDate|                  ts|
+----------+--------------------+
|09/18/2017|2017-09-18 00:00:...|
|          |                null|
+----------+--------------------+

The conversion is doing good, but if the value is empty , I'm getting null after casting.

Is there any way to return empty if the source value is empty.

1 Answer 1

1

you can use when function as below

import org.apache.spark.sql.functions._
val ts = unix_timestamp($"sDate","MM/dd/yyyy").cast("timestamp")
df.withColumn("ts", when(ts.isNotNull, ts).otherwise(lit("empty"))).show()

which would give you output as

+----------+-------------------+
|     sDate|                 ts|
+----------+-------------------+
|09/18/2017|2017-09-18 00:00:00|
|          |              empty|
+----------+-------------------+
Sign up to request clarification or add additional context in comments.

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.