让我们为您创建这个PySpark DataFrame
。to_date
您必须从functions
模块导入-
步骤 0:导入这 4 个函数 -
from pyspark.sql.functions import to_date, date_format, concat, lit
步骤1:
from pyspark.sql.functions import to_date, date_format, concat, lit
values = [('12/2/2018',),('12/7/2018',)]
df = sqlContext.createDataFrame(values,['scheduled_date_plus_one'])
df = df.withColumn('scheduled_date_plus_one',to_date('scheduled_date_plus_one','MM/dd/yyyy'))
df.printSchema()
root
|-- scheduled_date_plus_one: date (nullable = true)
df.show()
+-----------------------+
|scheduled_date_plus_one|
+-----------------------+
| 2018-12-02|
| 2018-12-07|
+-----------------------+
正如我们在 中看到的.printSchema()
,我们有日期date
格式。因此,作为我们的第一步,我们创建了所需的DataFrame
.
第 2 步:scheduled_date_plus_one
从date
格式转换为string
格式,以便我们可以连接T02:00:00Z
到它。date_format
将日期转换为所需格式的字符串。我们拿了yyyy-MM-dd
.
df = df.withColumn('scheduled_date_plus_one',date_format('scheduled_date_plus_one',"yyyy-MM-dd"))
df.printSchema()
root
|-- scheduled_date_plus_one: string (nullable = true)
df.show()
+-----------------------+
|scheduled_date_plus_one|
+-----------------------+
| 2018-12-02|
| 2018-12-07|
+-----------------------+
.printSchema()
上面显示了scheduled_date_plus_one
转换为string
格式,现在我们可以做concatenation
部分了。
第 3 步:连接 - 为此,我们使用concat
函数。注意 - 您必须T02:00:00Z
在lit()
函数中屏蔽,因为我们没有连接两列。
df = df.withColumn('scheduled_date_plus_one',concat('scheduled_date_plus_one',lit('T02:00:00Z')))
df.show()
+-----------------------+
|scheduled_date_plus_one|
+-----------------------+
| 2018-12-02T02:00:00Z|
| 2018-12-07T02:00:00Z|
+-----------------------+