在pyspark中读取datetime列作为stringType并将其转换为给出空记录的datetime



我正在阅读一个API调用,其中datetime列中的日期如下格式2016 - 07 - 27 t11:34:33z + 0000

现在我正在使用定义自定义模式创建一个数据框架

StructField("xyz",TimestampType(),True),  
StructField("abc",TimestampType(),True)

数据框正在创建,但当我调用操作它给出错误。

org.apache.spark.SparkException: Job aborted due to stage failure: Task 6 in stage 73040.0 failed 4 times, most recent failure: Lost task 6.3 in stage 73040.0 (TID 408627, 10.239.145.102, executor 12): org.apache.spark.api.python.PythonException: 'TypeError: field xyz: TimestampType can not accept object '2016-07-27T11:34:50Z+0000' in type <class 'str'>'. Full traceback below:

尝试:我尝试使用模式类型创建数据框架作为stringType的datetime列的工作,但当我将其转换为datetime它给出空值。

df_mod = df_mod.withColumn("xyz",df_mod['xyz'].cast(TimestampType()))

这是给空值。

在创建dataframe时使用stringtypedata

请帮助我如何用这种格式创建数据框架2016-07-27T11:34:33Z+0000,模式类型为时间戳。

您必须将此字符串2016-07-27T11:34:33Z+0000转换为unix_timestamp的历元时间,以便将其转换为TimestamptType。棘手的是你必须传递一个正确的日期格式。

df = spark.createDataFrame([
(1, '2016-07-27T11:34:33Z+0000'),
], 's int, a string')
+---+-------------------------+
|s  |a                        |
+---+-------------------------+
|1  |2016-07-27T11:34:33Z+0000|
+---+-------------------------+
import pyspark.sql.functions as F
(df
.withColumn('a', F.unix_timestamp('a', "yyyy-MM-dd'T'HH:mm:ss'Z'Z").cast('timestamp'))
.show()
)
+---+-------------------+
|  s|                  a|
+---+-------------------+
|  1|2016-07-27 04:34:33|
+---+-------------------+

最新更新