转换HH:mm:ss,以秒为单位

时间:2016-01-07 08:33:03

标签: scala apache-spark

我使用以下脚本从yyyy-MM-dd HH:mm:ss日期格式中提取HH:mm:ss

import java.sql.Time

case class Transactions(creationTime: Time)

val formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

def parseTransac(line: String): (Transactions) = {
   val fields = line.split(',')
   val creationTime = new Time(formatter.parse(fields(0)).getTime())
   val transactions = Transactions(creationTime)
   (transactions)
}

因此,例如2009-01-15 15:45:23将返回15:45:23

如何以秒(56723)代替HH:mm:ss

获得结果

3 个答案:

答案 0 :(得分:2)

根据Jesper的建议,这是解决方案:

import java.sql.Time    

case class Transactions(creationSeconds: Int )

val formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

def parseTransac(line: String): (Transactions) = {
   val fields = line.split(',')
   val fullDateTime = new Time(formatter.parse(fields(0)).getTime())
   val creationTime = fullDateTime.toString.split(':')
   val creationSeconds = creationTime(0).toInt*3600 + creationTime(1).toInt*60 + creationTime(2).toInt
   val transactions = Transactions(creationSeconds)
   (transactions)
}

这是另一种基于Dipankar提示的解决方案:

import java.sql.Time
import org.joda.time.DateTime

case class Transactions(creationTime: Int)

val formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

def parseTransac(line: String): (Transactions) = {
   val fields = line.split(',')
   val fullDatTime = new DateTime(formatter.parse(fields(0)).getTime())
   val fromMidnight = fullDatTime.withTimeAtStartOfDay()
   val duration = new Duration(fromMidnight, fullDatTime)
   val creationTime = duration.toStandardSeconds().getSeconds()
   val transactions = Transactions(creationTime)
   (transactions)
}

答案 1 :(得分:1)

您也可以使用简单的正则表达式执行此操作。

case class Transactions(creationTime: Int)

val format = "\\d{4}-\\d{2}-\\d{2}\\s(\\d{1,2}):(\\d{1,2}):(\\d{1,2})".r

def parseTransac(line: String): (Transactions) = {
  val fields = line.split(',')

  val format(h, m, s) = fields(0)

  Transactions(s.toInt + m.toInt * 60 + h.toInt * 3600)
}

答案 2 :(得分:1)

快速单线:

scala> "15:45:23".split(":").map(_.toInt).reduceLeft((x,y) => x*60 +y)
res0: Int = 56723