我已经看到(这里: How to convert Timestamp to Date format in DataFrame? )在日期类型中转换时间戳的方法,但是,至少对我来说,它不起作用。
这是我试过的:
# Create dataframe
df_test = spark.createDataFrame([('20170809',), ('20171007',)], ['date',])
# Convert to timestamp
df_test2 = df_test.withColumn('timestamp',func.when((df_test.date.isNull() | (df_test.date == '')) , '0')\
.otherwise(func.unix_timestamp(df_test.date,'yyyyMMdd')))\
# Convert timestamp to date again
df_test2.withColumn('date_again', df_test2['timestamp'].cast(stypes.DateType())).show()
但这在列 date_again
中返回 null :
+--------+----------+----------+
| date| timestamp|date_again|
+--------+----------+----------+
|20170809|1502229600| null|
|20171007|1507327200| null|
+--------+----------+----------+
知道什么失败了吗?
原文由 Luis A.G. 发布,翻译遵循 CC BY-SA 4.0 许可协议
下列的:
不起作用,因为它类型不一致 - 第一个子句返回
string
而第二个子句返回bigint
。因此,它将始终返回NULL
如果data
是NOT NULL
并且不为空。它也已过时 - SQL 函数是
NULL
并且格式错误是安全的。无需额外检查。在 Spark 2.2 或更高版本中你不需要中间步骤: