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
On this page
Show code in
Every code block on the page follows this.
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
Input: signups
| user | signup_raw | last_login |
|---|---|---|
| ana | 01/03/2025 | 2025-03-10 08:30:00 |
| bo | 15/02/2025 | 2025-03-01 22:05:00 |
| cy | 2025-02-20 | 2025-02-28 13:45:00 |
| di | 31/12/2024 | nullnull: 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:
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
| Letter | Means | Example for 2024-12-30 09:05:07 |
|---|---|---|
| yyyy | Calendar year | 2024 |
| YYYY | Week-based year | 2025 (the week containing Dec 30 belongs to 2025) |
| MM | Month | 12 |
| mm | Minute | 05 |
| dd | Day of month | 30 |
| DD | Day of year | 365 |
| HH | Hour 0-23 | 09 |
| hh | Hour 1-12 (use with a) | 09 |
| ss | Second | 07 |
| EEE / EEEE | Day name | Mon / Monday |
| MMM | Month name | Dec |
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)andtimestamp_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 toUTCon every job so results do not depend on where the cluster runs. to_utc_timestampandfrom_utc_timestampconvert between UTC and a named zone such asAsia/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?"
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?"
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?"
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."
unix_timestamp values, or timestamp subtraction.Check yourself
3 questionsWhat 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
- Label Late ShipmentsDates Easy
- Late Data in the Raw ZoneData Lake Medium
- Files VACUUM Can DeleteLakehouse Medium
Keep going
Up next · Clean and type · lesson 4 of 5 · 4 min readwhen / otherwise
CASE WHEN logic inside a column: first match wins, and a missing otherwise means null.
Related lessons
trunc / add_monthsPySpark functions · 5 min read
cast and schemasStructured Streaming · 8 min read
Watermarks and late data
Previous: String functions
Primary sources: Datetime patterns · functions.to_date · functions.date_format