如何找到两个日期之间的周差异

时间:2016-11-29 02:47:41

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

我有一个数据帧,在unixtime中有两个列日期,我想找到这两列之间的星期差异。 SparkSQL中有一个weekOfYear UDF,但只有当两个日期都在同一年时才有用。我怎样才能找到周差异?

P.S。我正在使用Scala Spark。

2 个答案:

答案 0 :(得分:1)

由于您有UNIXTIME日期格式,我们可以执行此表达式。

((date1-date2)/(60*60*24*7)).toInt

编辑: 使用示例

更新此答案
   spark.udf.register("weekdiff", (from: Long, to: Long) => ((from - to) / (604800)).toInt)
   //  60*60*24*7 => 604800
   df.withColumn("weekdiff", weekdiff(df("date1_col_name"), df("date2_col_name")))

答案 1 :(得分:1)

您可以采用为此创建自定义UDF的方法:

scala> val df=sc.parallelize(Seq((1480401142453L,1480399932853L))).toDF("date1","date2")
df: org.apache.spark.sql.DataFrame = [date1: bigint, date2: bigint]

scala> df.show
+-------------+-------------+
|        date1|        date2|
+-------------+-------------+
|1480401142453|1480399932853|
+-------------+-------------+


scala> val udfDateDifference=udf((date1:Long,date2:Long)=>((date1-date2)/(60*60*24*7)).toInt
     | 
     | )
udfDateDifference: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function2>,IntegerType,Some(List(LongType, LongType)))

scala> val resultDF=df.withColumn("dateDiffernece",udfDateDifference(df("date1"),df("date2")))
resultDF: org.apache.spark.sql.DataFrame = [date1: bigint, date2: bigint ... 1 more field]

scala> resultDF.show
+-------------+-------------+--------------+
|        date1|        date2|dateDiffernece|
+-------------+-------------+--------------+
|1480401142453|1480399932853|             2|
+-------------+-------------+--------------+

因此你可以获得不同!