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.
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()year returns the year of a date, timestamp or date-like string as an integer, and it accepts the string column directly. to_date returns a DATE, unix_timestamp returns epoch seconds as a long, and from_unixtime expects epoch seconds as input and returns a string.
Source: docs.databricks.com2.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?
weekday counts from Monday = 0, so Saturday is 5 and Sunday is 6. The 1 and 7 pair belongs to dayofweek, and 6 and 7 would be right only for ISO numbering shifted by none, which weekday is not.
“An INTEGER where 0 = Monday and 6 = Sunday.”Source: docs.databricks.com
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.
| Field and aliases | Returns |
|---|---|
| YEAR, Y, YEARS, YR, YRS | The year field |
| MONTH, MON, MONS, MONTHS | The month field (1 - 12) |
| DAY, D, DAYS | The day of the month field (1 - 31) |
| DAYOFWEEK, DOW | Sunday(1) to Saturday(7) |
| DAYOFWEEK_ISO, DOW_ISO | Monday(1) to Sunday(7) |
| DOY | The day of the year (1 - 365/366) |
| WEEK, W, WEEKS | ISO 8601 week-of-week-based-year |
| MINUTE, M, MIN, MINS, MINUTES | The 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.
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?
In extract and date_part, M is an alias for MINUTE, so the call returns the minute (8). To get the month, use MON or MONTH. Upper-case M means month only inside a datetime pattern.
“dbf.date_part(dbf.lit('M'), df.ts).alias('minute')”Source: docs.databricks.com
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.
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?
from_unixtime turns epoch seconds into a string for that moment in the current time zone, so the same row prints a different local time under UTC than under Los Angeles. Epoch seconds count from UTC, but the output string is shown in the session zone.
“to a string representing the timestamp of that moment in the current system time zone in the given format.”Source: docs.databricks.com
Sources
(10)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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.
“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.
“Ranges from 1 for a Sunday through to 7 for a Saturday”
↩︎ Day of week: dayofweek, weekday and ISO numbering - 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 - 5.
“> SELECT dayofweek('2009-07-30'); 5”
↩︎ Day of week: dayofweek, weekday and ISO numbering - 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 - 7.
“field | pyspark.sql.Column | selects which part of the source should be extracted.”
↩︎ Extracting any field with extract and date_part - 8.
“The date_part function is a synonym for the SQL standard extract function.”
↩︎ Extracting any field with extract and date_part - 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
“dbf.date_part(dbf.lit('M'), df.ts).alias('minute')”
↩︎ Checkpoint