【问题标题】:In Scala, how do I create a column of date arrays of monthly dates between a start and end date?在 Scala 中,如何在开始日期和结束日期之间创建一列包含每月日期的日期数组?
【发布时间】:2019-10-22 17:43:38
【问题描述】:

在 Spark Scala 中,我正在尝试创建一个列,其中包含开始日期和结束日期(含)之间的每月日期数组。

例如,如果我们有 2018-02-07 和 2018-04-28,则数组应包含 [2018-02-01, 2018-03-01, 2018-04-01]。

除了每月版本,我还想创建一个季度版本,即 [2018-1, 2018-2]。

输入数据示例:

id startDate endDate
1_1 2018-02-07 2018-04-28
1_2 2018-05-06 2018-05-31
2_1 2017-04-13 2017-04-14

预期(每月)产出 1:

id startDate endDate dateRange
1_1 2018-02-07 2018-04-28 [2018-02-01, 2018-03-01, 2018-04-01]
1_1 2018-05-06 2018-05-31 [2018-05-01]
2_1 2017-04-13 2017-04-14 [2017-04-01]

最终预期(每月)输出 2:

id Date
1_1 2018-02-01 
1_1 2018-03-01
1_1 2018-04-01
1_2 2018-05-01
2_1 2017-04-01

我有 spark 2.1.0.167、Scala 2.10.6 和 JavaHotSpot 1.8.0_172。

我已尝试在此处对类似(日级)问题实施多个答案,但我正在努力让每月/每季度的版本正常工作。

下面从 start 和 endDate 创建一个数组并将其分解。但是,我需要展开一个包含所有每月(每季度)日期的列。

val df1 = df.select($"id", $"startDate", $"endDate").
// This just creates an array of start and end Date
withColumn("start_end_array"), array($"startDate", $"endDate").
withColumn("start_end_array"), explode($"start_end_array"))

感谢您提供任何线索。

【问题讨论】:

    标签: java scala apache-spark explode date-range


    【解决方案1】:
    case class MyData(id: String, startDate: String, endDate: String, list: List[String])
    val inputData = Seq(("1_1", "2018-02-07", "2018-04-28"), ("1_2", "2018-05-06", "2018-05-31"), ("2_2", "2017-04-13", "2017-04-14"))
    inputData.map(x => {
      import java.time.temporal._
      import java.time._
      val startDate = LocalDate.parse(x._2)
      val endDate = LocalDate.parse(x._3)
      val diff = ChronoUnit.MONTHS.between(startDate, endDate)
      var result = List[String]();
      for (index <- 0 to diff.toInt) {
        result = (startDate.getYear + "-" + (startDate.getMonth.getValue + index) + "-01") :: result
      }
      new MyData(x._1, x._2, x._3, result)
    }).foreach(println)
    

    【讨论】:

    • 如果范围跨越一年怎么办
    猜你喜欢
    • 1970-01-01
    • 2018-10-16
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多