【问题标题】:convert date into desired format in pyspark [duplicate]在pyspark中将日期转换为所需的格式[重复]
【发布时间】:2020-12-28 09:34:15
【问题描述】:

我有如下数据框并使用 pyspark 2.4

Name    doj
kevin   08/15/2013
George  06/21/2014

df.printSchema()
 -- Name (String)
 -- dob (String)

我想将 doj 转换为 YYYY-MM-DD 格式,并确保我需要使用 pyspark 将 doj 转换为 Datetype 而不是 String。是否有任何特定功能可用?感谢您的回复

【问题讨论】:

  • 有没有尝试使用date_format?

标签: python apache-spark pyspark apache-spark-sql


【解决方案1】:

使用to_date()函数。

df.show()
#+------+----------+
#|  Name|       doj|
#+------+----------+
#| Kevin|08/15/2013|
#|George|06/21/2014|
#+------+----------+

from pyspark.sql.functions import *

df.withColumn("doj",to_date(col("doj"),'MM/dd/yyyy')).show()
#+------+----------+
#|  Name|       doj|
#+------+----------+
#| Kevin|2013-08-15|
#|George|2014-06-21|
#+------+----------+
df.withColumn("doj",to_date(col("doj"),'MM/dd/yyyy')).printSchema()
#root
# |-- Name: string (nullable = true)
# |-- doj: date (nullable = true)

【讨论】:

    【解决方案2】:
    def dateconv(x):
            if x == None:
                x = 'null'
                return x
            else:
                return x.strftime('%Y-%M-%D')
    dateconv(doj)
    

    在python中类似的东西,我做了这个

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多