【问题标题】:Get time duration in scala在scala中获取持续时间
【发布时间】:2020-08-07 01:03:24
【问题描述】:

我有一个由 date_time 组成的变量。现在我想用 current_time 来计算 date_time 的小时数。在 scala 中实现这一目标的最佳方法是什么?

val create_time = "2020-08-05 10:10:10"

假设 current_time 如下:

val current_time = "2020-08-06 10:10:10"

现在我预计持续时间以小时为单位。我可以使用 to_timestamp() 使用 spark 数据帧来实现这一点,但想看看我们如何在 scala 中做到这一点。

val df = Seq(("2020-08-01 12:01:19"), ("2020-08-05 12:01:19"), ("2020-08-06 16:44:55"), ("2020-08-06 16:50:59")).toDF("input_timestamp")


df.withColumn("input_timestamp", to_timestamp(col("input_timestamp")))
  .withColumn("current_timestamp", current_timestamp().as("current_timestamp"))
  .withColumn("DiffInSeconds", current_timestamp().cast(LongType) - col("input_timestamp").cast(LongType)) 
  .withColumn("DiffInHours",col("DiffInSeconds")/3600D)
  .withColumn("DiffInDays",round(col("DiffInHours")/24)).show(false)


+-------------------+-----------------------+-------------+------------------+----------+
|input_timestamp    |current_timestamp      |DiffInSeconds|DiffInHours       |DiffInDays|
+-------------------+-----------------------+-------------+------------------+----------+
|2020-08-01 12:01:19|2020-08-06 20:25:14.775|462235       |128.3986111111111 |5.0       |
|2020-08-05 12:01:19|2020-08-06 20:25:14.775|116635       |32.39861111111111 |1.0       |
|2020-08-06 16:44:55|2020-08-06 20:25:14.775|13219        |3.6719444444444442|0.0       |
|2020-08-06 16:50:59|2020-08-06 20:25:14.775|12855        |3.5708333333333333|0.0       |
+-------------------+-----------------------+-------------+------------------+----------+

【问题讨论】:

    标签: java scala


    【解决方案1】:

    Scala 解决方案。

    import java.time.LocalDateTime
    import java.time.format.DateTimeFormatter
    import java.time.temporal.ChronoUnit.HOURS
    
    val start = LocalDateTime.parse("2020-08-05 10:10:10"
                  ,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
    val stop  = LocalDateTime.now  //current_time
    
    val between = HOURS.between(start, stop)
    //between: Long = 32
    

    【讨论】:

      【解决方案2】:

      如果您使用 Java 8 及更高版本,则处理时间和时差的标准方法似乎是使用 Java time

      相关堆栈溢出帖:

      What's the standard way to work with dates and times in Scala? Should I use Java types or there are native Scala alternatives?

      【讨论】:

        猜你喜欢
        • 2023-03-11
        • 1970-01-01
        • 2012-03-14
        • 2011-04-09
        • 1970-01-01
        • 2021-12-27
        • 2014-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多