我正在尝试将字符串转换为日期类型。我在代码下面尝试。
from pyspark.sql import SparkSession
from pyspark.sql.functions import to_date, date_format
# Create a SparkSession
spark = SparkSession.builder.getOrCreate()
# Sample DataFrame with the string column
data = [("09-Aug-96",)]
df = spark.createDataFrame(data, ["date_string"])
# Convert string to date type
df = df.withColumn("date", to_date(df.date_string, "dd-MMM-yy"))
# Format the date as "dd-MM-yyyy"
df = df.withColumn("formatted_date", date_format(df.date, "dd-MM-yyyy"))
# Update the year part to four digits
df = df.withColumn("updated_date", date_format(df.date, "dd-MM-yyyy"))
# Show the result
df.show(truncate=False)
结果:
+-----------+----------+--------------+------------+
|date_string|date |formatted_date|updated_date|
+-----------+----------+--------------+------------+
|09-Aug-96 |2096-08-09|09-08-2096 |09-08-2096 |
+-----------+----------+--------------+------------+
但我希望是1996年。即以这种格式09-08-1996。同样,如果是05-Sep-23,我希望它是05-09-2023。
2条答案
按热度按时间qcuzuvrc1#
有一种简单粗暴的方法可以实现所需的输出,即使用
when().otherwise()
。但问题是,数据不应该有1900年至1923年等日期。例如,您无法通过输入格式区分01-Jan-1923
和01-Jan-2023
。这里有一个例子
你首先检查字符串日期中的年份,如果年份在0和(比如)25之间,你可以在字符串日期中的年初连接一个
"20"
。lymnna712#