我正在尝试将列类型从字符串更改为日期。我咨询过以下人士的答案:
- 如何将 DataFrame 中的列类型从字符串更改为日期? https://stackoverflow.com/questions/36948012/how-to-change-the-column-type-from-string-to-date-in-dataframes
- 为什么我从 date_format() PySpark 函数得到空结果? https://stackoverflow.com/questions/36094413/why-i-get-null-results-from-date-format-pyspark-function
当我尝试应用链接 1 中的答案时,我得到了 null 结果,因此我引用了链接 2 中的答案,但我不明白这部分:
output_format = ... # Some SimpleDateFormat string
from pyspark.sql.functions import col, unix_timestamp, to_date
#sample data
df = sc.parallelize([['12-21-2006'],
['05-30-2007'],
['01-01-1984'],
['12-24-2017']]).toDF(["date_in_strFormat"])
df.printSchema()
df = df.withColumn('date_in_dateFormat',
to_date(unix_timestamp(col('date_in_strFormat'), 'MM-dd-yyyy').cast("timestamp")))
df.show()
df.printSchema()
输出是:
root
|-- date_in_strFormat: string (nullable = true)
+-----------------+------------------+
|date_in_strFormat|date_in_dateFormat|
+-----------------+------------------+
| 12-21-2006| 2006-12-21|
| 05-30-2007| 2007-05-30|
| 01-01-1984| 1984-01-01|
| 12-24-2017| 2017-12-24|
+-----------------+------------------+
root
|-- date_in_strFormat: string (nullable = true)
|-- date_in_dateFormat: date (nullable = true)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)