将时间戳转换为spark数据帧中的日期

Lui*_*.G. 9 apache-spark pyspark

我在这里看到:如何在DataFrame中将时间戳转换为日期格式?转换datetype中的时间戳的方法,但至少对我来说,它不起作用.

这是我尝试过的

# 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()
Run Code Online (Sandbox Code Playgroud)

但是这会在date_again列中返回null:

+--------+----------+----------+
|    date| timestamp|date_again|
+--------+----------+----------+
|20170809|1502229600|      null|
|20171007|1507327200|      null|
+--------+----------+----------+
Run Code Online (Sandbox Code Playgroud)

什么失败了?

hi-*_*zir 14

以下:

func.when((df_test.date.isNull() | (df_test.date == '')) , '0')\
  .otherwise(func.unix_timestamp(df_test.date,'yyyyMMdd'))
Run Code Online (Sandbox Code Playgroud)

不起作用,因为它是类型不一致 - 第一个子句string在第二个子句返回时返回bigint.因此,NULL如果dataNOT NULL而非空,它将始终返回.

它也是过时的 - SQL函数NULL和格式错误的格式安全.无需额外检查.

In [1]: spark.sql("SELECT unix_timestamp(NULL, 'yyyyMMdd')").show()
+----------------------------------------------+
|unix_timestamp(CAST(NULL AS STRING), yyyyMMdd)|
+----------------------------------------------+
|                                          null|
+----------------------------------------------+


In [2]: spark.sql("SELECT unix_timestamp('', 'yyyyMMdd')").show()
+--------------------------+
|unix_timestamp(, yyyyMMdd)|
+--------------------------+
|                      null|
+--------------------------+
Run Code Online (Sandbox Code Playgroud)

并且您不需要Spark 2.2或更高版本中的中间步骤:

from pyspark.sql.functions import to_date

to_date("date", "yyyyMMdd")
Run Code Online (Sandbox Code Playgroud)


Ram*_*jan 11

你应该做以下事情

>>> df_test2.withColumn('date_again', func.from_unixtime('timestamp').cast(DateType())).show()
+--------+----------+----------+
|    date| timestamp|date_again|
+--------+----------+----------+
|20170809|1502216100|2017-08-09|
|20171007|1507313700|2017-10-07|
+--------+----------+----------+
Run Code Online (Sandbox Code Playgroud)

和架构是

>>> df_test2.withColumn('date_again', func.from_unixtime('timestamp').cast(DateType())).printSchema()
root
 |-- date: string (nullable = true)
 |-- timestamp: string (nullable = true)
 |-- date_again: date (nullable = true)
Run Code Online (Sandbox Code Playgroud)


Gra*_*non 5

对于pyspark:

假设您有一个字段名称:“ DateTime”,它将日期显示为日期和时间

在您的df中添加一个新字段,其中显示“ DateOnly”列,如下所示:

 from pyspark.sql.functions  import date_format
    df.withColumn("DateOnly", date_format('DateTime', "yyyyMMdd")).show()
Run Code Online (Sandbox Code Playgroud)

这将在df中显示一个名为DateOnly的新列-日期为yyyymmdd形式