CertKeen

Fabric Analytics Engineer (DP-600) · Free practice question 5 of 12

Converting strings to dates in PySpark

A PySpark DataFrame df has a string column OrderDateText with values such as 2026-03-14. You need a new column OrderDate of the date type for loading into a Delta table. Which statement should you use?

  1. A.df = df.withColumnRenamed("OrderDateText", "OrderDate")
  2. B.df = df.withColumn("OrderDate", to_date(col("OrderDateText"), "yyyy-MM-dd"))
  3. C.df = df.withColumn("OrderDate", col("OrderDateText").cast("string"))
  4. D.df = df.select("OrderDateText").alias("OrderDate")
Show answer and explanation

Correct answer: B. df = df.withColumn("OrderDate", to_date(col("OrderDateText"), "yyyy-MM-dd"))

Why: withColumn adds a column, and to_date parses the string with the yyyy-MM-dd pattern into a date value. Renaming the column keeps it as a string, and casting to string doesn't change the type. Selecting with an alias also leaves the data as text and drops the other columns.

More free Fabric Analytics Engineer (DP-600) questions