Databricks Data Engineer Associate Question 158
Select 2You are working with a DataFrame in Databricks that contains a column named 'event_time' with timestamp values. You need to extract the year, month, and day as separate columns from this timestamp. Which of the following options correctly retrieves this information?
- A
df.withColumn('year', year(col('event_time'))).withColumn('month', month(col('event_time'))).withColumn('day', dayofmonth(col('event_time')))
- B
df.withColumn('year', extract_year(col('event_time'))).withColumn('month', extract_month(col('event_time'))).withColumn('day', extract_day(col('event_time')))
- C
df.select(year(col('event_time')).alias('year'), month(col('event_time')).alias('month'), dayofmonth(col('event_time')).alias('day'))
- D
df.withColumn('year', col('event_time').year()).withColumn('month', col('event_time').month()).withColumn('day', col('event_time').day())
- E
df.withColumn('year', col('event_time').getYear()).withColumn('month', col('event_time').getMonth()).withColumn('day', col('event_time').getDay())
Show answer and explanation
Correct answers: A, C
Explanation
To extract calendar data (year, month, day) from a timestamp column in a Spark DataFrame, you can use the Spark SQL functions year, month, and dayofmonth. These functions can be used with withColumn to add new columns or with select to directly retrieve the extracted values with aliases. Other methods or function names are invalid in this context.
- A. Correct.
Correct. This uses the Spark SQL functions
year,month, anddayofmonth, which are the standard methods to extract calendar data from timestamps in Spark. - B. Incorrect.
Incorrect.
extract_year,extract_month, andextract_dayare not valid Spark SQL functions. The correct functions areyear,month, anddayofmonth. - C. Correct.
Correct. This approach also uses the Spark SQL functions
year,month, anddayofmonthbut retrieves the extracted values by selecting them directly with aliases. - D. Incorrect.
Incorrect. While
colis valid, the functions.year(),.month(), and.day()are not valid methods for extracting calendar data in PySpark. - E. Incorrect.
Incorrect. The methods
.getYear(),.getMonth(), and.getDay()are not supported for extracting calendar data from Spark DataFrame columns.