With pd.to_datetime in pandas 3.0, how do format, errors='coerce' and unit='s' handle an event log of mixed date strings and epoch seconds?
answer
- one layout for the whole column
- the first non-missing value decides
- bad rows become NaT, silently
- epoch numbers need a unit
- the ignore option is gone
basics
~10 spd.to_datetime applies one format to the whole column, guessed from the first non-missing value unless format= is given; errors='coerce' turns non-matching rows into NaT, and unit='s' reads integers as seconds since 1970.
solid answer
~40 sWithout `format`, `pd.to_datetime` guesses one layout from the first non-missing string and applies it to every row; a row in another layout raises `ValueError` ("doesn't match format") by default. With `errors="coerce"` those rows become `NaT` silently, so I count new missing values before trusting the result. For a log with two known layouts I parse each with an explicit `format` and combine them with `fillna`; `format="ISO8601"` covers ISO variants and `format="mixed"` parses each element separately, which is slower and riskier. Epoch seconds need `unit="s"` (milliseconds need `"ms"`), and adding `utc=True` makes the result tz-aware UTC. In pandas 3.0, `errors="ignore"` no longer exists: only `"raise"` and `"coerce"` remain.
code
python · 14 linesimport pandas as pd
raw = pd.Series(["2025-03-14", "2025-03-15", "15/03/2025", "not a date", None])
guessed = pd.to_datetime(raw, errors="coerce")
print(guessed.isna().sum() - raw.isna().sum()) # 2 rows silently lost
iso = pd.to_datetime(raw, format="%Y-%m-%d", errors="coerce")
dmy = pd.to_datetime(raw, format="%d/%m/%Y", errors="coerce")
parsed = iso.fillna(dmy)
print(raw[parsed.isna() & raw.notna()]) # only 'not a date' is left
epoch = pd.Series([1741942800, 1741946400, None])
print(pd.to_datetime(epoch, unit="s", utc=True))go deeper
Remember the three arguments: format for a known layout, errors='coerce' to turn bad rows into NaT, unit='s' for epoch seconds.
Explain that the format is guessed once from the first non-missing value, how to parse two known layouts and combine them, and why errors='ignore' disappeared in pandas 3.0.
Show the audit habit: count NaT before and after coercion, inspect the failed strings, and prove the epoch unit against a known row before shipping.
Decide where parsing rules live, one helper per source with its format and unit, so silent coercion cannot spread across a team's pipelines.
## The scenario An event log arrives with a `received` column holding date strings in more than one layout (`"2025-03-14"` from one source, `"15/03/2025"` from another, a few junk values) and an `epoch` column holding Unix timestamps in seconds. Both must become real datetimes. **`pd.to_datetime`** handles both, but its defaults decide what happens to the awkward rows. ## How the format is chosen Since pandas 2.0, `pd.to_datetime` parses a column with **one consistent format**: - If you pass **`format=`** (a strftime pattern such as `"%Y-%m-%d"` or `"%d/%m/%Y"`), that pattern is used for every row. - If you do not, pandas **guesses the format from the first non-missing string** and applies the guess to the whole column. - If no format can be guessed and there is more than one value, it warns (`UserWarning`) that each element will be parsed individually. The guess is not re-done per row. So with `"2025-03-14"` first, the row `"15/03/2025"` does not match the guessed ISO layout, and the default **`errors="raise"`** stops the parse with a `ValueError` whose message reads `time data "15/03/2025" doesn't match format "%Y-%m-%d"` and suggests the alternatives below. ## errors: raise or coerce | `errors=` | non-matching row becomes | when to use | |---|---|---| | `"raise"` (default) | an exception for the whole call | you expect clean input and want to hear otherwise | | `"coerce"` | `NaT` (pandas' missing datetime) | you will inspect and handle the failures yourself | **`errors="coerce"` hides problems by design.** A whole source in another layout can quietly turn into `NaT`. The defensive habit is to compare missing counts before and after: 1. Count `raw.isna().sum()` before parsing. 2. Count `parsed.isna().sum()` after parsing. 3. Look at `raw[parsed.isna() & raw.notna()]` to see exactly which strings failed. In **pandas 3.0, `errors="ignore"` is removed** from `to_datetime` (and from `to_timedelta` and `to_numeric`). In 2.x it returned the input unchanged on failure and was deprecated in 2.2 with the advice to catch the exception explicitly. Code that still passes it now fails, so it must move to `"raise"` with a `try`/`except`, or to `"coerce"` plus the check above. ## Handling several layouts on purpose When the layouts are known, parse each one explicitly and combine: ```python iso = pd.to_datetime(raw, format="%Y-%m-%d", errors="coerce") dmy = pd.to_datetime(raw, format="%d/%m/%Y", errors="coerce") parsed = iso.fillna(dmy) ``` Each pass is fast and strict, and a value that matches neither stays `NaT` for you to review. Two built-in alternatives exist: - **`format="ISO8601"`** accepts any ISO 8601 string even when the strings differ in detail (with or without a time, with or without fractional seconds). - **`format="mixed"`** infers the format for each element separately. The docstring calls this risky: `"01/02/2025"` may be read as January or February depending on `dayfirst`, which is a preference rather than a strict rule. Use it only together with `dayfirst` and a check of the output. `exact` cannot be combined with `"ISO8601"` or `"mixed"`. ## Epoch numbers and unit Integers or floats are read as offsets from **`origin="unix"`** (1970-01-01) in the given **`unit`**: `"s"`, `"ms"`, `"us"`, `"ns"` or `"D"`. Getting the unit wrong usually does not raise: seconds read as milliseconds land in January 1970, and milliseconds read as seconds land tens of thousands of years ahead, so check a known row. Points to remember: - A missing epoch (`NaN`) becomes `NaT`. - The result is **naive**: it shows UTC clock time but carries no zone. Add **`utc=True`** to get a tz-aware UTC column you can later convert to local time. - Float epochs can lose sub-second precision; integer epochs are exact. - The `unit` strings are not the same as `format` codes. In pandas 3.0 the result keeps the unit of the input, so `unit="s"` gives a second-resolution column. That matters only when converting back to integers. ## A checklist for interviews - Name the first-value format guess and why one odd source breaks it. - Prefer an explicit `format` per known layout over `"mixed"`. - Treat `errors="coerce"` as a promise to audit the `NaT` values it creates. - Use `unit=` for epochs, and `utc=True` when the numbers are UTC instants. - Know that `errors="ignore"` is gone in pandas 3.0. Reading the same columns straight from a CSV with `parse_dates` is covered with CSV import; attaching and converting time zones after parsing is the next question on this topic.
- In pandas, what happens if epoch milliseconds are parsed with pd.to_datetime(..., unit='s')?Each number is read as seconds, so the values sit 1000 times too far from 1970: a current millisecond epoch lands around the year 57169. In pandas 3.0 the result keeps second resolution, which can represent that year, so nothing raises. The opposite slip, seconds read as `unit="ms"`, quietly gives dates in January 1970. Check one known row after choosing the unit.
- Why does pd.to_datetime raise 'Mixed timezones detected' on strings with +02:00 and +01:00 offsets, and what fixes it?A datetime column holds one time zone, and strings from a zone with daylight saving carry two different offsets across the year. Without `utc=True`, pandas refuses to pick one and raises `ValueError`. Passing `utc=True` converts every value to the same UTC instant, after which `.dt.tz_convert` can show any local zone.
- Thinks pandas guesses a separate format for every row by default
- Uses errors='coerce' without counting the NaT values it creates
- Still passes errors='ignore' to pd.to_datetime in pandas 3.0
- Reaches for format='mixed' as the safe default for any messy column
- Parses epoch numbers without unit= and trusts the result
- Believes unit='s' output is already time-zone aware
Assumes pandas 3.0: errors='ignore' was deprecated in 2.2 and removed from to_datetime in 3.0, leaving only 'raise' and 'coerce'.