What you will be able to do
- Pick between from_unixtime and unix_timestamp based on whether you start from epoch seconds or end with them
- Parse string columns into DATE and TIMESTAMP values with to_date and to_timestamp, and work out why a parse returns NULL
- Write datetime patterns that use the right letter case and letter count, and format values with date_format
Key concept
Datetime pattern — A datetime pattern is a string of pattern letters, like yyyy-MM-dd HH:mm:ss, that tells Spark how a date or time is laid out as text. Each conversion between text and dates or epoch seconds reads or writes text through one of these patterns, and a pattern that does not match the data makes the conversion fail.
1.Epoch seconds and strings: from_unixtime and unix_timestamp
Event times in a Spark pipeline usually come in one of three shapes: a long column counting seconds since the Unix epoch, a readable string such as 2024-03-15 14:30:00, or a typed DATE or TIMESTAMP value. Most date bugs come from calling a function on the wrong shape. Two functions handle conversion to and from epoch seconds, and they work in opposite directions.
from_unixtime turns a number into text. It takes a column of seconds counted from 1970-01-01 00:00:00 UTC and returns a string showing that moment in the current time zone, using the format you give it. The format is optional and defaults to yyyy-MM-dd HH:mm:ss. So from_unixtime(col("event_epoch")) gives a full date-time string, and from_unixtime(col("event_epoch"), "yyyy-MM-dd") gives only the date, still as a string. That one call is what a new string column added with withColumn needs when the source column holds epoch seconds.
unix_timestamp turns text into a number. It parses a time string using a pattern, which also defaults to yyyy-MM-dd HH:mm:ss, and returns Unix time in seconds as a long integer. It uses the default time zone and locale. Two more behaviours matter. It returns null when parsing fails, and if you call it with no argument it returns the current timestamp. The pattern describes the input string, not the output. A value like 2015-04-08 12:12:12 parses with the default pattern, a date-only value needs yyyy-MM-dd, and a pattern like MM/dd/yyyy HH:mm:ss applied to dash-separated data simply fails.
import pyspark.sql.functions as sf
df = spark.createDataFrame([('2015-04-08',)], ['dt'])
df.select('*', sf.unix_timestamp('dt', 'yyyy-MM-dd')).show()
+----------+------------------------------+
| dt|unix_timestamp(dt, yyyy-MM-dd)|
+----------+------------------------------+
|2015-04-08| 1428476400|
+----------+------------------------------+None of the other date functions reads epoch seconds. date_format is defined for date, timestamp and string inputs. to_date and to_timestamp parse values according to a datetime pattern. unix_timestamp produces seconds rather than reading them. When the input is a long of epoch seconds, from_unixtime is the only function here built for it.
Checkpoint 1 of 6· Fill the gap
The dt column holds date-only strings such as '2015-04-08'. You need a new column with that date as a long count of seconds since the Unix epoch. Which function completes this sample?
import pyspark.sql.functions as sf
df = spark.createDataFrame([('2015-04-08',)], ['dt'])
df.select('*', sf. ? ('dt', 'yyyy-MM-dd')).show()unix_timestamp parses a string using the pattern you give it, here 'yyyy-MM-dd' to match the input, and returns epoch seconds as a long. from_unixtime goes the other way, from seconds to a formatted string. date_format and from_utc_timestamp do not return epoch seconds.
Source: docs.databricks.comCheckpoint 2 of 6· Exam question
A pipeline stores event times as Unix epoch seconds in a LongType column named event_epoch. An analyst needs a new column event_date holding the date as a string in yyyy-MM-dd format. Which code correctly creates it?
df.withColumn("event_date", ___)
Correct answer: A — from_unixtime(col("event_epoch"), "yyyy-MM-dd")
- A.
from_unixtime()is built specifically to convert a numeric count of seconds since the Unix epoch into a formatted date/time string, so it correctly turns the epoch column into ayyyy-MM-ddstring. - B.
to_date()parses a string column according to the supplied pattern; it does not interpret a numeric long value as seconds since the epoch, so applying it to a raw epoch column returns null for every row. - C.
unix_timestamp()converts a formatted date/time string into epoch seconds, which is the reverse of the conversion needed here, and it does not accept a numeric epoch column as meaningful input. - D.
date_format()expects aDateTypeorTimestampTypecolumn to reformat; called on a plainLongTypeepoch column it cannot interpret the value and yields null or an error rather than a valid date string. - E.
to_timestamp()parses a string according to the given pattern rather than treating a numeric input as seconds since the epoch, so the raw epoch long is not converted correctly by this call.
2.Parsing strings into DATE and TIMESTAMP with to_date
to_date converts a column into DateType, and to_timestamp converts one into TimestampType. Both take an optional format. Without a format they follow the normal casting rules, so to_date(col) is the same as col.cast("date"). With a format, the format must describe the string exactly as it is written. The input can be a plain string column. Neither function needs the value cast to a date first, and to_date('2016-12-31', 'yyyy-MM-dd') shows that a date-only string parses directly.
The two functions differ in what they keep. to_date('2009-07-30 04:17:52') returns 2009-07-30, so the time of day is gone. That makes to_date the right tool when you want a date column and the wrong first step toward epoch seconds: once hours, minutes and seconds are dropped, no later cast can bring them back. to_timestamp keeps them, and unix_timestamp goes straight from the string to seconds.
Spark never guesses a layout. Reading 25/03/2024 with MM/dd/yyyy asks for month 25, so the value does not parse. With spark.sql.ansi.enabled set to false the result is NULL. With ANSI mode on, the same mismatch raises CANNOT_PARSE_TIMESTAMP instead. Rows whose day is 12 or lower are worse: they parse without complaint into the wrong date, with day and month swapped. The fix is to give the pattern that matches the data, dd/MM/yyyy for day-first strings. Toggling spark.sql.ansi.enabled does not help, because that setting only decides whether a malformed value comes back as NULL or raises an error; it never changes how the layout is read. Wrapping the column in another function does not help either, and neither does switching to unix_timestamp. That function also needs a pattern that matches, and it also returns null when parsing fails.
-- Parsing a non-default date format
> SELECT to_date('31/12/2016', 'dd/MM/yyyy');
2016-12-31Checkpoint 3 of 6· Check yourself
Some rows of a string column hold day-first dates such as '25/03/2024', and to_date(col("raw_date"), "MM/dd/yyyy") returns NULL for them. ANSI mode is off. Which change makes them parse into the correct dates?
to_date reads plain strings directly. The format has to describe the layout of the input, so day-first data needs dd/MM/yyyy. Turning ANSI mode on only changes the NULL into a CANNOT_PARSE_TIMESTAMP error. unix_timestamp also needs a pattern that matches, and it returns null when parsing fails.
“Converts a pyspark.sql.Column into pyspark.sql.types.DateType using the optionally specified format. Specify formats according to datetime pattern.”Source: docs.databricks.com
Checkpoint 4 of 6· Exam question
A raw log column log_time (string) stores values like "2024-03-15 14:30:00" in the format yyyy-MM-dd HH:mm:ss. A downstream system requires a LongType column epoch_seconds holding the number of seconds since the Unix epoch. Which code correctly creates it?
df.withColumn("epoch_seconds", ___)
Correct answer: A — unix_timestamp(col("log_time"), "yyyy-MM-dd HH:mm:ss")
- A.
unix_timestamp()parses a formatted date/time string using the given pattern and returns the matching number of seconds since the Unix epoch, which is exactly the conversionlog_timeneeds. - B.
from_unixtime()converts a numeric epoch value into a formatted string, the reverse of what is required here, and it does not accept a string column likelog_timeas its first argument. - C.
to_date()keeps only the calendar date and discards the time-of-day portion, and casting the resultingDateTypetolongyields the number of days since 1970-01-01 rather than seconds, so the time component and correct unit are both lost. - D. The pattern
MM/dd/yyyy HH:mm:ssdoes not match the actualyyyy-MM-dd HH:mm:sslayout oflog_time, so the parse fails and the expression returns null instead of the correct epoch value. - E.
date_format()reformats a date/timestamp value into another string; it does not produce a numeric epoch value, so the result is a formatted string rather than the requiredLongTypeseconds count.
Checkpoint 5 of 6· Exam question
A CSV column raw_date (string) stores day-first dates such as "25/03/2024" (dd/MM/yyyy). A developer runs:
df.withColumn("parsed_date", to_date(col("raw_date"), "MM/dd/yyyy"))
and finds parsed_date is null for most rows, including "25/03/2024". What is the correct fix, and why?
Correct answer: A — Change the format string to dd/MM/yyyy to match the day-first layout of raw_date; to_date() returns null whenever the pattern does not match the string's actual layout.
- A.
raw_datestores day-first values, so the pattern must placeddbeforeMM; a mismatched pattern order is the standard reasonto_date()fails to parse otherwise valid strings and returns null. - B.
to_date()is designed to accept aStringTypecolumn as its normal use case and parses it according to the pattern; the failure here comes from a wrong pattern, not from receiving a string input. - C.
to_date()works correctly on pure date-only strings without any time component; the presence or absence of a time portion is not the cause of the null values in this scenario. - D.
unix_timestamp()still requires an explicit format argument that matches the string layout; it does not auto-detect arbitrary date layouts, so swapping functions without fixing the pattern would not resolve the issue. - E. The legacy time parser policy changes which parsing engine is used for certain ambiguous patterns, but it does not make a
MM/dd/yyyypattern correctly interpret day-first strings like"25/03/2024".
3.Datetime pattern letters and date_format
The same pattern letters are used by every function on this page and by the CSV and JSON readers, so a dateFormat option set when reading files into a DataFrame follows the same rules. Two things decide what a pattern means: the case of each letter and how many times it is repeated.
| Letter | Meaning | Example output |
|---|---|---|
| y | year | 2020; 20 |
| M | month-of-year | 7; 07; Jul; July |
| m | minute-of-hour | 30 |
| d | day-of-month | 28 |
| D | day-of-year | 189 |
| H | hour-of-day (0-23) | 0 |
| h | clock-hour-of-am-pm (1-12) | 12 |
| E | day-of-week | Tue; Tuesday |
| s | second-of-minute | 55 |
| S | fraction-of-second | 978 |
The number of repeated letters sets the output. For months, M prints 1 through 12 with no padding, MM pads to 01, MMM gives the short name Jan, and MMMM gives January. Text fields follow the same idea: fewer than four letters gives the short form (E gives Tue), exactly four gives the full form (EEEE gives Tuesday), and five or more fails. Years work differently. yy prints the last two digits, and when parsing it reads them as a year from 2000 to 2099. So a two-digit-year pattern turns 99 into 2099, not 1999.
date_format is the output side of these rules. It converts a date, timestamp or date-like string into a string in whatever pattern you give, so 'MM/dd/yyyy' turns 2015-04-08 into 04/08/2015. Because it always returns a string, use it for display and export, not for numbers. To get the year as an integer, the specialised extractor year is the better choice.
from pyspark.sql import functions as dbf
df = spark.createDataFrame([('2015-04-08',), ('2024-10-31',)], ['dt'])
df.select("*", dbf.typeof('dt'), dbf.date_format('dt', 'MM/dd/yyyy')).show()The pattern used upper-case MM where it needed lower-case mm. MM is month-of-year and mm is minute-of-hour, so the minutes slot was filled with the month. The correct pattern is yyyy-MM-dd HH:mm:ss.
Checkpoint 6 of 6· Check yourself
A report needs DATE values such as 2024-03-15 shown as '15 March 2024'. Which date_format pattern produces that string?
Lower-case dd is day-of-month, and exactly four M letters give the full month name, 'March'. MMM gives the short name 'Mar', MM gives the number 03, and five M letters fail.
“Exactly 4 pattern letters will use the full text form, typically the full description”Source: docs.databricks.com
Sources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“a string representing the timestamp of that moment in the current system time zone in the given format”
↩︎ Epoch seconds and strings: from_unixtime and unix_timestamp“format to use to convert to (default: yyyy-MM-dd HH:mm:ss)”
↩︎ Epoch seconds and strings: from_unixtime and unix_timestamp“Converts the number of seconds from unix epoch (1970-01-01 00:00:00 UTC) to a string”
↩︎ Exam trap 1 - 2.
“Convert time string with given pattern ('yyyy-MM-dd HH:mm:ss', by default) to Unix time stamp (in seconds)”
↩︎ Epoch seconds and strings: from_unixtime and unix_timestamp“using the default timezone and the default locale, returns null if failed”
↩︎ Epoch seconds and strings: from_unixtime and unix_timestamp“If timestamp is None, then it returns current timestamp.”
↩︎ Epoch seconds and strings: from_unixtime and unix_timestamp“unix time as long integer.”
↩︎ Epoch seconds and strings: from_unixtime and unix_timestamp - 3.
“Converts a date/timestamp/string to a value of string”
↩︎ Epoch seconds and strings: from_unixtime and unix_timestamp“Whenever possible, use specialized functions like year.”
↩︎ Datetime pattern letters and date_format“Converts a date/timestamp/string to a value of string in the format specified by the date format given by the second argument.”
↩︎ Exam trap 2 - 4.
“Converts a pyspark.sql.Column into pyspark.sql.types.DateType using the optionally specified format.”
↩︎ Parsing strings into DATE and TIMESTAMP with to_date“Equivalent to col.cast("date").”
↩︎ Parsing strings into DATE and TIMESTAMP with to_date“Converts a pyspark.sql.Column into pyspark.sql.types.DateType using the optionally specified format. Specify formats according to datetime pattern.”
↩︎ Checkpoint - 5.
“Converts a column into TimestampType using the optionally specified format.”
↩︎ Parsing strings into DATE and TIMESTAMP with to_date - 6.
“expr: A STRING expression representing a date.”
↩︎ Parsing strings into DATE and TIMESTAMP with to_date“> SELECT to_date('2009-07-30 04:17:52'); 2009-07-30”
↩︎ Parsing strings into DATE and TIMESTAMP with to_date“In Databricks Runtime, if spark.sql.ansi.enabled is false, the function returns NULL instead of an error for malformed dates.”
↩︎ Parsing strings into DATE and TIMESTAMP with to_date“CANNOT_PARSE_TIMESTAMP: Raised when fmt is provided but the input string does not match the given format pattern.”
↩︎ Parsing strings into DATE and TIMESTAMP with to_date“If your data uses a different format, such as dd/MM/yyyy or MM-dd-yyyy, specify the matching fmt argument.”
↩︎ Exam trap 3 - 7.
“CSV and JSON data sources use the pattern string for parsing and formatting datetime content.”
↩︎ Datetime pattern letters and date_format“The count of pattern letters determines the format.”
↩︎ Datetime pattern letters and date_format“Exactly 4 pattern letters will use the full text form, typically the full description”
↩︎ Datetime pattern letters and date_format“For parsing, this will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.”
↩︎ Datetime pattern letters and date_format“Zero padding is added for months 1-9.”
↩︎ Datetime pattern letters and date_format“Databricks uses pattern letters in the following table for date and timestamp parsing and formatting”
↩︎ Key concept