Call pd.to_datetime(df["col"], errors="coerce") and assign it back to the column (df["col"] = pd.to_datetime(df["col"], errors="coerce")), passing format="%Y-%m-%d" (or format="ISO8601" / format="mixed" in Pandas 2.0+) for faster, unambiguous parsing and utc=True when normalizing timezone-aware strings.
Basic Example
import pandas as pd
df = pd.DataFrame({
"created_at": ["2026-01-15", "2026-11-29", "invalid_date", None],
"sales": [100, 250, 80, 140],
})
# 1. Recommended: Convert column to datetime64[ns] safely (invalid values become NaT)
df["created_at"] = pd.to_datetime(df["created_at"], errors="coerce")
print(df.dtypes)
# Output:
# created_at datetime64[ns]
# sales int64
print(df)
# created_at sales
# 0 2026-01-15 100
# 1 2026-11-29 250
# 2 NaT 80
# 3 NaT 140
# 2. Explicit format string (10x–50x faster on large DataFrames & prevents day/month swaps):
df_custom = pd.DataFrame({"dt": ["29/11/2026 17:30", "01/02/2026 08:15"]})
df_custom["dt"] = pd.to_datetime(df_custom["dt"], format="%d/%m/%Y %H:%M", errors="coerce")
Key Details & Edge Cases
- Pandas 2.0+ strict per-element format inference (
format="mixed"vs. explicitformat=):- Starting in Pandas 2.0,
pd.to_datetime()infers a single consistent format from the first non-null elements—so a column mixing"2026-01-15"and"2026-01-15 14:30:00"raisesValueError: time data "..." doesn't match format "%Y-%m-%d". - Pass
format="ISO8601"(for ISO strings with varying precision/offsets) orformat="mixed"(for heterogeneous string formats) when formats vary across rows, or pass an explicitstrftimeformat (format="%Y-%m-%d") for maximum speed.
- Starting in Pandas 2.0,
errors="raise"vs.errors="coerce"(and removal oferrors="ignore"in Pandas 2.2+):- By default (
errors="raise"), a single malformed string ("N/A","TBD","") aborts the entire conversion withValueError. Always passerrors="coerce"on messy real-world data to turn unparseable entries intoNaT(Not a Time), then inspectdf["col"].isna().sum(). - Note:
errors="ignore"was deprecated in Pandas 2.2 and removed in Pandas 3.0—never use it.
- By default (
- Ambiguous DD/MM/YYYY vs. MM/DD/YYYY dates (
dayfirst=True):- Without an explicit
format=,"01/02/2026"defaults to US month-first (Jan 2, 2026). Passformat="%d/%m/%Y"(preferred) ordayfirst=Truewhen parsing European/Commonwealth day-first dates.
- Without an explicit
- Mixed timezone offsets (
+05:00,-04:00,Z) requireutc=True:- If a column contains timestamps from multiple timezones (e.g.,
"2026-11-29T12:00:00Z"and"2026-11-29T17:00:00+05:00"),pd.to_datetime()fails or produces anobjectcolumn of Pythondatetimeobjects unless you passutc=True, which normalizes every timestamp into a single vectorizeddatetime64[ns, UTC]column.
- If a column contains timestamps from multiple timezones (e.g.,
- Converting Unix epoch integers/floats (
unit="s"orunit="ms"):- When converting numeric Unix timestamps (e.g.,
1764418200), always specifyunit="s"(seconds),unit="ms"(milliseconds), orunit="ns"—otherwisepd.to_datetime()defaults to nanoseconds and interprets1764418200as January 1, 1970!
- When converting numeric Unix timestamps (e.g.,
Comparison of pd.to_datetime() Options & Related Methods
| Pattern | Handles Messy / Invalid Strings? | Speed on Large Columns | Output Dtype | Best Used When |
|---|---|---|---|---|
pd.to_datetime(s, format="...", errors="coerce") (Recommended) |
Yes (NaT on bad rows) |
Fastest (explicit C-level strptime) | datetime64[ns] (or [s]/[us]) |
Production pipelines with a known date/timestamp format and potentially dirty rows. |
pd.to_datetime(s, format="ISO8601", utc=True) |
Only if errors="coerce" is added |
Fast | datetime64[ns, UTC] |
API logs and JSON exports containing ISO 8601 strings with mixed offsets or fractional seconds. |
pd.to_datetime(s, format="mixed", dayfirst=True, errors="coerce") |
Yes (NaT on bad rows) |
Moderate (per-row parser) | datetime64[ns] |
Heterogeneous user-entered or scraped dates mixing slashes, dashes, and month names. |
pd.to_datetime(s, unit="s", utc=True) |
With errors="coerce" |
Fastest | datetime64[ns, UTC] |
Numeric Unix epoch timestamps (specify unit="s" or unit="ms"). |
You must log in or register to comment.
