Skip to content
Bronze 4 min read · Dates 3 practice problems ↓

Parsing dates and timestamps

Dates often arrive as text: "2025-03-14", "14/03/2025", "Mar 14 2025". Until they are real dates you cannot add days, compare them reliably or group by month. This lesson shows how to turn text into dates and timestamps, how date patterns work, and how time zones change what you see.

Step 1 · PySpark functions · Bronze · Clean and type, lesson 3 of 5

Read first: cast and schemas (skip if you know it)

In plain words first

A note that says "14/03" is clear to a person, but is it March 14th or the 3rd of the 14th month? To be sure, you say how the note is written: "day, slash, month". Then anyone can turn it into a real calendar date, and count days from it.

In Spark, that description is the pattern, such as dd/MM/yyyy, and to_date uses it to turn text into a real date.

Dates, timestamps and strings

A DATE is a calendar day. A TIMESTAMP is an instant in time, shown in the session time zone. Strings that look like dates are just text: they sort correctly only in yyyy-MM-dd form, and you cannot add days to them. Parse once, early, and keep real date types.

Run the example

PySparkSpark SQL

Input: signups

usersignup_rawlast_login
ana01/03/20252025-03-10 08:30:00
bo15/02/20252025-03-01 22:05:00
cy2025-02-202025-02-28 13:45:00
di31/12/2024nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →
from pyspark.sql import functions as F
result = signups.select(
    "user",
    F.to_date("signup_raw", "dd/MM/yyyy").alias("signup_date"),
    F.to_timestamp("last_login").alias("login_ts"),
    F.date_format(F.to_timestamp("last_login"), "EEE HH:mm").alias("login_label"),
    F.datediff(
        F.to_date("last_login"), F.to_date("signup_raw", "dd/MM/yyyy")
    ).alias("days_to_login"),
)
SELECT user,
       to_date(signup_raw, 'dd/MM/yyyy')        AS signup_date,
       to_timestamp(last_login)                 AS login_ts,
       date_format(last_login, 'EEE HH:mm')     AS login_label,
       datediff(to_date(last_login), to_date(signup_raw, 'dd/MM/yyyy')) AS days_to_login
FROM signups

Cy's signup is null: 2025-02-20 does not match dd/MM/yyyy. Di has no login, so everything computed from it is null.

Mixed formats in one column

Try each format in turn and take the first that parses. coalesce returns the first non-null:

PySparkSpark SQL · Several formats
signup_date = F.coalesce(
    F.to_date("signup_raw", "dd/MM/yyyy"),
    F.to_date("signup_raw", "yyyy-MM-dd"),
)
coalesce(to_date(signup_raw, 'dd/MM/yyyy'), to_date(signup_raw, 'yyyy-MM-dd'))

In Spark 4.0 with ANSI mode on, to_date raises an error for a string that does not match; use try_to_timestamp or try_to_date style functions where available, or set the pattern per source so mismatches cannot happen.

Pattern letters

LetterMeansExample for 2024-12-30 09:05:07
yyyyCalendar year2024
YYYYWeek-based year2025 (the week containing Dec 30 belongs to 2025)
MMMonth12
mmMinute05
ddDay of month30
DDDay of year365
HHHour 0-2309
hhHour 1-12 (use with a)09
ssSecond07
EEE / EEEEDay nameMon / Monday
MMMMonth nameDec
Watch out: YYYY-MM-dd looks right and works for most of the year, then prints 2025-12-30 for 30 December 2024. It is a classic bug that only appears in the last days of December. Always use lower-case yyyy.

Formatting for output

date_format(col, pattern) turns a date or timestamp into a string. Keep it for the last step (reports, file names, labels): once formatted, the column is text again. To group by month, prefer trunc(col, "month"), which stays a date and sorts correctly.

Epoch seconds and time zones

  • unix_timestamp(col) returns seconds since 1970-01-01 UTC; from_unixtime(secs) and timestamp_seconds(secs) go back.
  • Epoch milliseconds (common in Kafka and APIs) need dividing by 1000 first, or use timestamp_millis.
  • Parsing a timestamp string with no offset interprets it in spark.sql.session.timeZone. Set it to UTC on every job so results do not depend on where the cluster runs.
  • to_utc_timestamp and from_utc_timestamp convert between UTC and a named zone such as Asia/Kolkata.

Common mistakes

  • YYYY instead of yyyy — Week-based year: wrong for a few days around New Year.
  • mm instead of MM — Minutes instead of months.
  • Comparing date strings in dd/MM/yyyy form — "02/01/2025" sorts after "01/12/2025". Parse first.
  • Leaving the session time zone at the cluster default — The same job gives different timestamps in different regions. Set it to UTC.

Key takeaways

  • to_date and to_timestamp parse strings; mismatches become null (or errors under ANSI).
  • yyyy is the year, YYYY is the week-based year; MM is month, mm is minute.
  • Use coalesce over several to_date calls for mixed formats.
  • Format with date_format only at the end; set the session time zone to UTC.

Interview prep

THE QUESTION

"A report shows 2025 for orders placed on 30 December 2024. Why?"

The format pattern uses YYYY, the week-based year, instead of yyyy. 30 December 2024 falls in the first week of 2025. Fix the pattern, and add a test with dates around New Year. Mention mm vs MM as the other common pattern mistake.

Avoid: "a timezone problem". The symptom near New Year is the week-based year pattern, YYYY, not timezones.

Follow-ups · answer out loud, then open

Follow-up"to_date('2025-1-5', 'yyyy-MM-dd') fails. Why?"
Since Spark 3, parsing is strict: MM and dd expect two digits. In Spark 3 this raises an INCONSISTENT_BEHAVIOR_CROSS_VERSION error, because the old parser would have accepted it. In Spark 4.0 it raises CANNOT_PARSE_TIMESTAMP under ANSI mode, or returns null with ANSI off. Use yyyy-M-d, which accepts one or two digits, and try_to_timestamp where bad values should become null.
Scenario"Event timestamps come from many countries. How do you make daily reports consistent?"
Store timestamps as UTC instants, set spark.sql.session.timeZone explicitly instead of relying on the cluster's default, and convert to a local zone only for display or for business days defined locally, using from_utc_timestamp.
Trap"datediff(end, start) counts 24-hour periods between two timestamps."
It counts calendar date boundaries: it converts both to dates first. 23:59 to 00:01 the next day is 1. For elapsed time use the difference of unix_timestamp values, or timestamp subtraction.

Check yourself

3 questions

What does to_date("2025-02-20", "dd/MM/yyyy") return in classic Spark?

Show the answer

null. The string does not match the pattern, so the result is null.

Which pattern prints the calendar year?

Show the answer

yyyy. Lower-case yyyy is the year; upper-case YYYY is the week-based year.

What does "mm" mean in a pattern?

Show the answer

Minute. MM is month; mm is minute.

Practise this

Problems that use this, graded on hidden tests

See all 8 problems →

Keep going

Up next · Clean and type · lesson 4 of 5 · 4 min read
when / otherwise
CASE WHEN logic inside a column: first match wins, and a missing otherwise means null.

Related lessons

Previous: String functions

Primary sources: Datetime patterns · functions.to_date · functions.date_format