CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 3 · Lesson 15/32

    Extracting date components in Spark: year, dayofweek, extract and time zones

    Manipulate and utilize Date data type, such as Unix epoch to date string, and extract date component.

    8 min read
    3% of exam
    10 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Extract year, month and day of month as integers from date and timestamp columns
    • Tell apart the day-of-week numbering of dayofweek, weekday and DAYOFWEEK_ISO
    • Call extract and date_part with a Column field and the correct field names
    • Work out how the session time zone changes the components extracted from a timestamp

    1.Year, month and day of month as integers

    Breaking a date into parts is how most date logic in DataFrame code starts: grouping revenue by year, partitioning output by month, or filtering to the first of each month. Spark has one function per common part. year, month and dayofmonth (and its alias day) each take a date or timestamp column and return that part as an integer. An integer is what filters and groupings need. A formatted string such as date_format(dt, 'yyyy') looks the same when printed but is text, so the extractor is the better choice whenever the value will be compared or summed.

    These extractors accept either a Column or a column name, and the column may hold a date, a timestamp, or a date-like string. year is documented against four inputs: the strings '2015-04-08' and '2015-04-08 13:08:15', a Python datetime.date(2015, 4, 8), and a Python datetime.datetime(2015, 4, 8, 13, 8, 15). The result is always the year as an integer, so strings in the standard layout do not need converting first.

    year applied to a string column of ISO datespython
    from pyspark.sql import functions as dbf
    df = spark.createDataFrame([('2015-04-08',), ('2024-10-31',)], ['dt'])
    df.select("*", dbf.typeof('dt'), dbf.year('dt')).show()

    Checkpoint 1 of 4· Fill the gap

    The column dt holds ISO date strings. Which function completes this sample so the new column holds each row's year as an integer that you can filter or group on?

    from pyspark.sql import functions as dbf
    df = spark.createDataFrame([('2015-04-08',), ('2024-10-31',)], ['dt'])
    df.select("*", dbf.typeof('dt'), dbf. ? ('dt')).show()

    Sources12

    2.Day of week: dayofweek, weekday and ISO numbering

    Spark offers three ways to number the days of the week, and they disagree. dayofweek starts the week on Sunday: Sunday is 1 and Saturday is 7. weekday starts on Monday and counts from zero: Monday is 0 and Sunday is 6. ISO 8601 numbering, available as the DAYOFWEEK_ISO field of extract, starts on Monday and counts from one: Monday is 1 and Sunday is 7. weekday is defined as extract(DAYOFWEEK_ISO FROM expr) - 1.

    Thursday 30 July 2009 shows all three: dayofweek('2009-07-30') returns 5, extract(DAYOFWEEK_ISO ...) returns 4, and weekday returns 3. The difference matters as soon as the number goes into a filter. A weekend filter is dayofweek(dt).isin(1, 7) but weekday(dt).isin(5, 6). Mixing them up does not raise an error. It quietly selects the wrong days.

    Checkpoint 2 of 4· Check yourself

    A job keeps only weekend rows by filtering on weekday(dt). Which set of values selects Saturday and Sunday?

    Sources3456

    3.Extracting any field with extract and date_part

    extract and date_part pull any named field out of a date, timestamp or interval. date_part is a synonym for the SQL-standard extract. In PySpark the field argument is a Column, not a plain Python string, which is why the examples wrap the field name in lit. Field names are case-insensitive and have short aliases. Most fields come back as integers, but SECOND returns a DECIMAL(8, 6) so that fractional seconds survive.

    Common extract and date_part fields for DATE and TIMESTAMP sources
    Field and aliasesReturns
    YEAR, Y, YEARS, YR, YRSThe year field
    MONTH, MON, MONS, MONTHSThe month field (1 - 12)
    DAY, D, DAYSThe day of the month field (1 - 31)
    DAYOFWEEK, DOWSunday(1) to Saturday(7)
    DAYOFWEEK_ISO, DOW_ISOMonday(1) to Sunday(7)
    DOYThe day of the year (1 - 365/366)
    WEEK, W, WEEKSISO 8601 week-of-week-based-year
    MINUTE, M, MIN, MINS, MINUTESThe minutes field (0 - 59)

    The alias M is the one that catches people. In a datetime pattern, upper-case M means month. As an extract field, M means minute, and month is MON or MONTH. The reference example below labels date_part(lit('M'), ...) as minute. WEEK has its own catch: it is the ISO week, which starts on Monday, so early-January dates can fall in week 52 or 53 of the previous year.

    date_part with Column fields; note that 'M' is minute and 'month' is spelled outpython
    import datetime
    from pyspark.sql import functions as dbf
    df = spark.createDataFrame([(datetime.datetime(2015, 4, 8, 13, 8, 15),)], ['ts'])
    df.select(
    '*',
    dbf.date_part(dbf.lit('YEAR'), 'ts').alias('year'),
    dbf.date_part(dbf.lit('month'), 'ts').alias('month'),
    dbf.date_part(dbf.lit('WEEK'), 'ts').alias('week'),
    dbf.date_part(dbf.lit('D'), df.ts).alias('day'),
    dbf.date_part(dbf.lit('M'), df.ts).alias('minute'),
    dbf.date_part(dbf.lit('S'), df.ts).alias('second')
    ).show()

    Checkpoint 3 of 4· Check yourself

    A developer needs the month of a timestamp column and writes date_part(lit('M'), 'ts'). For the value 2015-04-08 13:08:15, what comes back?

    Sources786

    4.How the session time zone changes extracted values

    A TIMESTAMP marks a moment in time, and the hour, day or weekday of that moment depends on where you view it from. TIMESTAMP is the same type as TIMESTAMP_LTZ, a timestamp with time zone. When Spark extracts a field from one, it reads the moment in the session time zone. The same row can therefore report a different hour under a different zone, and close to midnight a different day of month and day of week too. This applies to dayofweek, weekday and extract alike. TIMESTAMP_NTZ is the separate type for a timestamp without time zone, and DATE is a third input type. The session-zone rule is stated only for TIMESTAMP_LTZ.

    The session time zone is the setting spark.sql.session.timeZone, and current_timezone() returns the value in effect. from_unixtime follows the same setting: it turns epoch seconds into a string for that moment in the session time zone. The reference example sets the zone to America/Los_Angeles before formatting a fixed epoch value and unsets it afterwards, so the printed string reflects Los Angeles local time and would differ under another zone. A job whose output depends on calendar days, such as daily partitions or a weekday filter, should set the session zone explicitly rather than inherit whatever the cluster default is.

    Setting the session time zone around an epoch-to-string conversionpython
    spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles")
    
    from pyspark.sql import functions as dbf
    df = spark.createDataFrame([(1428476400,)], ['unix_time'])
    df.select('*', dbf.from_unixtime('unix_time')).show()
    spark.conf.unset("spark.sql.session.timeZone")

    Checkpoint 4 of 4· Check yourself

    Identical data, identical code: both jobs run from_unixtime(col("event_epoch")). One session has spark.sql.session.timeZone set to UTC and the other has it set to America/Los_Angeles. How do the two outputs compare for the same row?

    Sources629

    Sources

    (10)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Extract the year of a given date/timestamp as integer.”
      ↩︎ Year, month and day of month as integers
      “col | pyspark.sql.Column or str | target date/timestamp column to work on.”
      ↩︎ Year, month and day of month as integers
    2. 2.
      “Extract the month of a given date/timestamp as integer.”
      ↩︎ Year, month and day of month as integers
      “Extract the day of the month of a given date/timestamp as integer.”
      ↩︎ Year, month and day of month as integers
      “Parses the timestamp with the format to a timestamp with time zone.”
      ↩︎ How the session time zone changes extracted values
      “Parses the timestamp with the format to a timestamp without time zone.”
      ↩︎ How the session time zone changes extracted values
      “Returns the current session local timezone.”
      ↩︎ How the session time zone changes extracted values
    3. 4.
      “This function is a synonym for extract(DAYOFWEEK_ISO FROM expr) - 1.”
      ↩︎ Day of week: dayofweek, weekday and ISO numbering
      “> SELECT weekday(DATE'2009-07-30'), extract(DAYOFWEEK_ISO FROM DATE'2009-07-30');”
      ↩︎ Day of week: dayofweek, weekday and ISO numbering
      “An INTEGER where 0 = Monday and 6 = Sunday.”
      ↩︎ Exam trap 1
      “An INTEGER where 0 = Monday and 6 = Sunday.”
      ↩︎ Checkpoint
    4. 6.
      “DAYOFWEEK_ISO, DOW_ISO: ISO 8601 based day of the week for datetime as Monday(1) to Sunday(7)”
      ↩︎ Day of week: dayofweek, weekday and ISO numbering
      “To return the three-letter acronym for the day of the week, use the dayname function.”
      ↩︎ Day of week: dayofweek, weekday and ISO numbering
      “If field is SECOND, a DECIMAL(8, 6). In all other cases, an INTEGER.”
      ↩︎ Extracting any field with extract and date_part
      “MONTH, MON, MONS, MONTHS: The month field (1 - 12)”
      ↩︎ Extracting any field with extract and date_part
      “it is possible for early-January dates to be part of the 52nd or 53rd week of the previous year”
      ↩︎ Extracting any field with extract and date_part
      “When extracting fields from a TIMESTAMP (TIMESTAMP_LTZ), the result is based on the session timezone.”
      ↩︎ How the session time zone changes extracted values
      “source: A DATE, TIME, TIMESTAMP, TIMESTAMP_NTZ, or INTERVAL expression.”
      ↩︎ How the session time zone changes extracted values
      “MINUTE, M, MIN, MINS, MINUTES: The minutes field (0 - 59)”
      ↩︎ Exam trap 2
    5. 7.
      “field | pyspark.sql.Column | selects which part of the source should be extracted.”
      ↩︎ Extracting any field with extract and date_part
    6. 8.
      “The date_part function is a synonym for the SQL standard extract function.”
      ↩︎ Extracting any field with extract and date_part
    7. 9.
      “spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles")”
      ↩︎ How the session time zone changes extracted values
      “to a string representing the timestamp of that moment in the current system time zone in the given format.”
      ↩︎ Checkpoint

    Also cited

    Ready to test yourself?

    Practise Databricks Certified Associate Developer for Apache Spark in quiz mode.

    Spotted a mistake, or was something unclear? Tell us.