首页 > 解决方案 > 在Scala中将时间戳值转换为双精度值

问题描述

所以我改变了TimeStamp的“t”,我必须把它转换成Double。我定义了这个类:

case class RawData(sessionId: String,
                   t: Double,
                   channel: Int,
                   signalName: String,
                   physicalValue: Double,
                   messageId: Long,
                   vehicleId: String)

而且我在这段代码中将“t”转换为double时遇到问题:

def raw(): Unit = {
    import rawData.sqlContext.implicits._
//TODO solve timestamp
    val datDMY = rawData
      .map(row => {
        cal.setTimeInMillis(row.t.)
        RawDataExtended(
          row.sessionId,
          row.t,
          row.channel,
          row.signalName,
          row.physicalValue,
          row.messageId,
          cal.get(Calendar.YEAR),
          cal.get(Calendar.MONTH) + 1,
          cal.get(Calendar.DAY_OF_MONTH)
        )
      })

标签: scaladataframetimestampdouble

解决方案


也许这可以帮助你:

  case class InputModel(id: Int, time: Timestamp)
  case class Foo(id: Int, timeLong: Long, timeDouble: Double)

  val xs = Seq((1, Timestamp.from(Instant.now())), (2, Timestamp.from(Instant.now()))).toDF("id", "time")

  val ys = xs
    .select('id, 'time cast (DataTypes.LongType) as "timeLong", 'time cast (DataTypes.DoubleType) as "timeDouble")
    .as[Foo]

  val zs = xs
    .as[InputModel]
    .map(row => {
      Foo(row.id, row.time.getTime.toLong, row.time.getTime.toDouble)
    })

  xs.show(false)
  ys.show(false)
  zs.show(false)

尽管在转换为 Double 时要小心时区并且要精确 - 请注意 Timestamp 与 Double 相比它是如何表示为 Long 的。


推荐阅读