3

I have a csv file with datetime column: "2011-05-02T04:52:09+00:00".

I am using scala, the file is loaded into spark DataFrame and I can use jodas time to parse the date:

val sqlContext = new SQLContext(sc)
import sqlContext.implicits._
val df = new SQLContext(sc).load("com.databricks.spark.csv", Map("path" -> "data.csv", "header" -> "true")) 
val d = org.joda.time.format.DateTimeFormat.forPattern("yyyy-mm-dd'T'kk:mm:ssZ")

I would like to create new columns base on datetime field for timeserie analysis.

In DataFrame, how do I create a column base on value of another column?

I notice DataFrame has following function: df.withColumn("dt",column), is there a way to create a column base on value of existing column?

Thanks

1

1 Answer 1

7
import org.apache.spark.sql.types.DateType
import org.apache.spark.sql.functions._
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat

val d = DateTimeFormat.forPattern("yyyy-mm-dd'T'kk:mm:ssZ")
val dtFunc: (String => Date) = (arg1: String) => DateTime.parse(arg1, d).toDate
val x = df.withColumn("dt", callUDF(dtFunc, DateType, col("dt_string")))

The callUDF, col are included in functions as the import show

The dt_string inside col("dt_string") is the origin column name of your df, which you want to transform from.

Alternatively, you could replace the last statement with:

val dtFunc2 = udf(dtFunc)
val x = df.withColumn("dt", dtFunc2(col("dt_string")))
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks for the post. I'm actually doing what you suggested, but got the following error: "scala.MatchError: java.util.Date (of class scala.reflect.internal.Types$TypeRef$$anon$6) "

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.