如何在Scala中将字符串转换为日期,以便我可以在SparkSQL中过滤?

时间:2017-09-28 06:32:51

标签: scala apache-spark apache-spark-sql

我希望能够像在普通SQL中一样过滤日期。那可能吗?我遇到了一个关于如何将字符串从文本文件转换为日期的问题。

import org.apache.spark._
import org.apache.spark.SparkContext._
import org.apache.spark.sql._
import org.apache.log4j._
import java.text._
//import java.util.Date
import java.sql.Date


object BayAreaBikeAnalysis {

  case class Station(ID:Int, name:String, lat:Double, longitude:Double, dockCount:Int, city:String, installationDate:Date)
  case class Status(station_id:Int, bikesAvailable:Int, docksAvailable:Int, time:String)

  val dateFormat = new SimpleDateFormat("yyyy-MM-dd")

  def extractStations(line: String): Station = {
    val fields = line.split(",",-1)
    val station:Station = Station(fields(0).toInt, fields(1), fields(2).toDouble, fields(3).toDouble, fields(4).toInt, fields(5), dateFormat.parse(fields(6)))
    return station
  }

  def extractStatus(line: String): Status = {
    val fields = line.split(",",-1)
    val status:Status = Status(fields(0).toInt, fields(1).toInt, fields(2).toInt, fields(3))
    return status
  }

  def main(args: Array[String]) {

    // Set the log level to only print errors
    //Logger.getLogger("org").setLevel(Level.ERROR)

    // Use new SparkSession interface in Spark 2.0      
    val spark = SparkSession
    .builder
    .appName("BayAreaBikeAnalysis")
    .master("local[*]")
    .config("spark.sql.warehouse.dir", "file:///C:/temp")
    .getOrCreate()

    //Load files into data sets
    import spark.implicits._
    val stationLines = spark.sparkContext.textFile("Data/station.csv")
    val stations = stationLines.map(extractStations).toDS().cache()

    val statusLines = spark.sparkContext.textFile("Data/status.csv")
    val statuses = statusLines.map(extractStatus).toDS().cache()

    //people.select("name").show()
    stations.select("installationDate").show()

    spark.stop()
  }   



}

显然字段(6).toDate()不能编译,但我不确定要使用什么。

3 个答案:

答案 0 :(得分:1)

我认为this post正是您所寻找的。

同样here您将找到一个很好的字符串解析教程。

希望这有帮助!

答案 1 :(得分:1)

以下是在scala中将字符串转换为日期的方法。

(1)如果是java.util.date: -

val date= new SimpleDateFormat("yyyy-MM-dd")
date.parse("2017-09-28")

(2)如果是joda的dateTime: -

DateTime.parse("09-28-2017")

答案 2 :(得分:1)

这是一个帮助函数,它接受表示日期的字符串并将其转换为时间戳

import java.sql.Timestamp
import java.util.TimeZone
import java.text.{DateFormat, SimpleDateFormat}

def getTimeStamp(timeStr: String): Timestamp = {

    val dateFormat: DateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"))

    val date: Option[Timestamp] = {
      try {
        Some(new Timestamp(dateFormat.parse(timeStr).getTime))
      } catch {
        case _: Exception => Some(Timestamp.valueOf("19700101'T'000000"))
      }
    }

    date.getOrElse(Timestamp.valueOf(timeStr))
  }

显然,您需要更改输入日期格式,从" yyyy-MM-dd' T' HH:mm:ss"你有任何日期字符串的格式。

希望这有帮助。