CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 3 · Lesson 15/32

    Converting Unix epoch seconds, date strings and DATE values in Spark

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

    12 min read
    3% of exam
    7 sources
    Published 21 Oct 2026
    Docs as of 30 Sep 2026

    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.

    unix_timestamp parsing a date-only string with an explicit pattern returns a long count of secondspython
    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()

    Checkpoint 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", ___)

    Sources123

    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.

    A day-first string parses once the pattern matches its layoutsql
    -- Parsing a non-default date format
    > SELECT to_date('31/12/2016', 'dd/MM/yyyy');
     2016-12-31

    Checkpoint 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?

    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", ___)

    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?

    Sources456

    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.

    Pattern letters whose upper- and lower-case forms mean different things
    LetterMeaningExample output
    yyear2020; 20
    Mmonth-of-year7; 07; Jul; July
    mminute-of-hour30
    dday-of-month28
    Dday-of-year189
    Hhour-of-day (0-23)0
    hclock-hour-of-am-pm (1-12)12
    Eday-of-weekTue; Tuesday
    ssecond-of-minute55
    Sfraction-of-second978

    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.

    date_format turns date strings into a US-style string layoutpython
    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()

    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?

    Sources73

    Sources

    (7)

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

    1. 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. 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
    3. 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. 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
      “Converts a pyspark.sql.Column into pyspark.sql.types.DateType using the optionally specified format. Specify formats according to datetime pattern.”
      ↩︎ Checkpoint
    5. 5.
      “Converts a column into TimestampType using the optionally specified format.”
      ↩︎ Parsing strings into DATE and TIMESTAMP with to_date
    6. 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. 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

    Continue to part 2 of 2

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

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