我正在尝试读取一个打印精美的 json,其中包含时间字段。我想在读取 json 本身时将时间戳列解释为时间戳字段。但是,当我 printSchema
例如 输入 json 文件 -
[{
"time_field" : "2017-09-30 04:53:39.412496Z"
}]
代码-
df = spark.read.option("multiLine", "true").option("timestampFormat","yyyy-MM-dd HH:mm:ss.SSSSSS'Z'").json('path_to_json_file')
df.printSchema()
的输出 -
root
|-- time_field: string (nullable = true)
我在这里错过了什么?
最佳答案
我自己对 timestampFormat
选项的体验是,它并不像宣传的那样有效。我会简单地将时间字段读取为字符串并使用 to_timestamp
进行转换,如下所示(具有稍微通用的示例输入):
# /path/to/jsonfile
[{
"id": 101, "time_field": "2017-09-30 04:53:39.412496Z"
},
{
"id": 102, "time_field": "2017-10-01 01:23:45.123456Z"
}]
在 Python 中:
from pyspark.sql.functions import to_timestamp
df = spark.read.option("multiLine", "true").json("/path/to/jsonfile")
df = df.withColumn("timestamp", to_timestamp("time_field"))
df.show(2, False)
+---+---------------------------+-------------------+
|id |time_field |timestamp |
+---+---------------------------+-------------------+
|101|2017-09-30 04:53:39.412496Z|2017-09-30 04:53:39|
|102|2017-10-01 01:23:45.123456Z|2017-10-01 01:23:45|
+---+---------------------------+-------------------+
df.printSchema()
root
|-- id: long (nullable = true)
|-- time_field: string (nullable = true)
|-- timestamp: timestamp (nullable = true)
在 Scala 中:
val df = spark.read.option("multiLine", "true").json("/path/to/jsonfile")
df.withColumn("timestamp", to_timestamp($"time_field"))
关于json - 在读取 json 时解释 Spark 中的时间戳字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53697388/