我正在尝试在 Spark 中进行时间戳差异,但它没有按预期工作。
下面是我正在尝试的方法
import org.apache.spark.sql.functions.*
df = df.withColumn("TimeStampDiff", from_unixtime(unix_timestamp(df.col("TimeStampHigh"), "HH:mm:ss").minus(unix_timestamp(df.col("TimeStampLow"), "HH:mm:ss")),"HH:mm:ss"))
Values
TimeStampHigh - 15:57:01
TimeStampLow - 00:11:57
它返回给我一个结果10:45:04
预期产出 -15:45:04
我的另一个选择是使用带有 Java 实现的 UDF。
任何指示都会有帮助。
那是因为from_unixtime https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions%24@from_unixtime(ut:org.apache.spark.sql.Column,f:String):org.apache.spark.sql.Column(强调我的):
将 unix 纪元 (1970-01-01 00:00:00 UTC) 的秒数转换为表示该时刻时间戳的字符串在当前系统时区以给定的格式。
显然,您的系统或 JVM 未配置为使用 UTC 时间。
您应该执行以下操作之一:
- 配置 JVM 以使用适当的时区(
-Duser.timezone=UTC
对彼此而言spark.executor.extraJavaOptions
and spark.driver.extraJavaOptions
).
- Set
spark.sql.session.timeZone
使用适当的时区。
Example:
scala> val df = Seq(("15:57:01", "00:11:57")).toDF("TimeStampHigh", "TimeStampLow")
df: org.apache.spark.sql.DataFrame = [TimeStampHigh: string, TimeStampLow: string]
scala> spark.conf.set("spark.sql.session.timeZone", "GMT-5") // Equivalent to your current settings
scala> df.withColumn("TimeStampDiff", from_unixtime(unix_timestamp(df.col("TimeStampHigh"), "HH:mm:ss").minus(unix_timestamp(df.col("TimeStampLow"), "HH:mm:ss")),"HH:mm:ss")).show
+-------------+------------+-------------+
|TimeStampHigh|TimeStampLow|TimeStampDiff|
+-------------+------------+-------------+
| 15:57:01| 00:11:57| 10:45:04|
+-------------+------------+-------------+
scala> spark.conf.set("spark.sql.session.timeZone", "UTC") // With UTC
scala> df.withColumn("TimeStampDiff", from_unixtime(unix_timestamp(df.col("TimeStampHigh"), "HH:mm:ss").minus(unix_timestamp(df.col("TimeStampLow"), "HH:mm:ss")),"HH:mm:ss")).show
+-------------+------------+-------------+
|TimeStampHigh|TimeStampLow|TimeStampDiff|
+-------------+------------+-------------+
| 15:57:01| 00:11:57| 15:45:04|
+-------------+------------+-------------+
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)