我有一个CSV,其中一个字段是特定格式的日期时间.我无法直接在我的Dataframe中导入它,因为它需要是一个时间戳.所以我将它作为字符串导入并将其转换为Timestamp这样的
import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.util.Date
import org.apache.spark.sql.Row
def getTimestamp(x:Any) : Timestamp = {
val format = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss")
if (x.toString() == "")
return null
else {
val d = format.parse(x.toString());
val t = new Timestamp(d.getTime());
return t
}
}
def convert(row : Row) : Row = {
val d1 = getTimestamp(row(3))
return Row(row(0),row(1),row(2),d1)
}
Run Code Online (Sandbox Code Playgroud)
使用Dataframe API或spark-sql有更好,更简洁的方法吗?上述方法需要创建RDD并再次为Dataframe提供架构.