QuestionQ294

VerifiedDeveloping Apache Spark™ DataFrame/DataSet API Applications

In what sequence should the following lines of code be executed to return a DataFrame containing a dayOfYear column—an integer representation of the day of the year—from column openDate from DataFrom storesDF?

Note that column openDate is an integer and represents a date in UNIX epoch format—the number of seconds since midnight on January 1st, 1970.

A sample of storesDF is shown below:

Question Image

Lines of code:

  1. storesDF.withColumn("openTimestamp", col("openDate").cast("Timestamp")) \
  2. storesDF.withColumn("dayOfYear", dayofyear(col("openDate")))
  3. storesDF.withColumn("openDateFormat", col("openDate").cast("Date")) \
  4. withColumn("dayOfYear", dayofyear(col("openTimestamp")))
  5. withColumn("dayOfYear", dayofyear(col("openDateFormat")))
  6. withColumn("dayOfYear", get_dayofyear(col("openDateFormat")))
Explanation

A Unix timestamp measured in seconds must be represented as a timestamp before extracting a calendar component. Casting openDate to Timestamp creates openTimestamp, and dayofyear(openTimestamp) returns the day of the year as an integer. Spark documents dayofyear as operating on a date or timestamp and returning an integer.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!