首页 > 解决方案 > 为什么 Spark SQL 中的 FROM_UNIXTIME 返回不同的日期/时间?

问题描述

有人可以解释为什么 FROM_UNIXTIME(0) 不返回1970-01-01 00:00:00。例如,

Seq(1).toDF("seq").select(
    from_unixtime(lit(0)).as("timestamp_1")
).show()

返回

+-------------------+
|        timestamp_1|
+-------------------+
|1969-12-31 16:00:00|
+-------------------+

这个函数的文档似乎也有点偏离。Spark 2.3.0文档1970-01-01 00:00:00,而最新文档 1969-12-31 16:00:00. 它是否取决于火花集群的时区设置?

编辑1:

spark.conf.get("spark.sql.session.timeZone")返回America/Los_Angeles。所以,我目前在 PST,PST 是 GMT-7.00。但是,from_unixtime(lit(0))与 UTC 相差 8 小时,而不是 7 小时。请注意,夏令时现在不适用。

标签: apache-sparkapache-spark-sql

解决方案


这是因为时区差异-

spark=2.4.5

  //I'm in GMT + 5:30
   Seq(1).toDF("seq").select(
      from_unixtime(lit(0)).as("timestamp_1")
    ).show()
    /**
      * +-------------------+
      * |        timestamp_1|
      * +-------------------+
      * |1970-01-01 05:30:00|
      * +-------------------+
      */

      // Use UTC
    spark.conf.set("spark.sql.session.timeZone", "UTC")
    Seq(1).toDF("seq").select(
      from_unixtime(lit(0)).as("timestamp_1")
    ).show()
    /**
      * +-------------------+
      * |        timestamp_1|
      * +-------------------+
      * |1970-01-01 00:00:00|
      * +-------------------+
      */

通过设置更新 1America/Los_Angeles

 spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles")
    Seq(1).toDF("seq").select(
      from_unixtime(lit(0)).as("timestamp_1")
    ).show()
    /**
      * +-------------------+
      * |        timestamp_1|
      * +-------------------+
      * |1969-12-31 16:00:00|
      * +-------------------+
      */
    println(TimeZone.getTimeZone("America/Los_Angeles"))
    // sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]
    // Please check offset which is -28800000 ms
    // 28800000 ms = 8 hours

推荐阅读