Sub topic 6
Parsing dates with pd.to_datetime
Dates in messy data usually arrive as text. This chapter shows how to turn that text into real datetime64 columns with pd.to_datetime, and how to avoid the usual traps: ambiguous day and month order, mixed formats, time zones, and values that silently become NaT.
It assumes you can create and index a DataFrame and Series, have read a CSV with pandas, and know the basics of astype and pd.to_numeric from earlier chapters. The examples were written for pandas 2.x. Where pandas 1.x or 3.x behave differently, the text says so.
Why use to_datetime instead of astype
A column of date strings has the object dtype (or string). You can't subtract such values, sort them chronologically, or group them by month. A datetime64 column supports all of these, and it exposes the .dt accessor for pulling out parts of a date.
astype("datetime64[ns]") works only when every value is already in a format pandas accepts, and it raises an error on the first bad value. pd.to_datetime gives you control over the format, the handling of bad values, time zones, and numeric timestamps. Use it for almost all date conversions.
The basic call
import pandas as pd
s = pd.Series(["2024-01-05", "2024-02-10", "bad", None])
dates = pd.to_datetime(s, format="%Y-%m-%d", errors="coerce")
print(dates)
print(dates.dtype)The first two values become timestamps. "bad" and None both become NaT, which stands for "not a time" and is the missing-value marker for datetime columns. The dtype is a datetime64 type, usually datetime64[ns].
The three arguments you will use most are:
format: astrftime-style pattern such as%Y-%m-%d. Passing it is faster and removes guessing.errors: what to do with values that don't parse.utc: whether to normalize everything to UTC.
Choosing the errors setting
| Setting | Behavior on an unparseable value | When to use it |
|---|---|---|
| `"raise"` (default) | Raises `ValueError` | You expect clean data and want to know immediately |
| `"coerce"` | Replaces it with `NaT` | You want the whole column converted and plan to inspect the failures |
| `"ignore"` | Returns the input unchanged | Avoid it. It is deprecated since pandas 2.2 and removed in 3.0 |
A common workflow is to use errors="coerce" and then check which values failed, as shown later in this chapter. Using coerce and never checking is how data quietly disappears.
The spine example applies the same pattern to a DataFrame column:
import pandas as pd
df = pd.DataFrame({"date": ["2024-01-05", "2024-02-10", "bad"]})
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d", errors="coerce")
print(df.dtypes)
print(df)Formats and the day/month ambiguity
The string 03/04/2024 is 4 March in the United States and 3 April in much of the rest of the world. pandas can't know which you mean, so it follows a rule, and the rule changed in version 2.0.
- In pandas 2.0 and later,
to_datetimeguesses the format from the first non-missing value and applies that single format to every element. If a later value doesn't match, it raises an error or, witherrors="coerce", returnsNaT. - In pandas 1.x, the parser tried each element separately. This was slower and could produce a column in which some rows were read as day-first and others as month-first, with no warning.
The best defense is to state the format yourself:
import pandas as pd
s = pd.Series(["03/04/2024", "25/04/2024"])
print(pd.to_datetime(s, format="%d/%m/%Y"))Both values parse as day/month/year. If you leave out format, pandas 2.x guesses month-first from 03/04/2024, and 25/04/2024 then fails because there is no month 25.
Two shortcuts exist for cases where you can't give a single format:
dayfirst=Truetells the guesser to prefer day-before-month for ambiguous strings. It is a hint, not a guarantee, and it doesn't replaceformat.yearfirst=Truedoes the same for year-first strings.
Common format codes
| Code | Meaning | Example |
|---|---|---|
| `%Y` | Four-digit year | 2024 |
| `%y` | Two-digit year | 24 |
| `%m` | Month number | 01 |
| `%d` | Day of month | 05 |
| `%H:%M:%S` | Hour, minute, second (24-hour) | 14:30:00 |
| `%b` / `%B` | Month name, short / full | Jan / January |
| `%z` | UTC offset | +0100 |
For example, "5 Jan 2024" needs format="%d %b %Y". Month names depend on the locale of the machine running the code, so English month names can fail to parse on a system configured for another language.
Mixed formats
If one column genuinely contains several layouts, pandas 2.x lets you say so:
import pandas as pd
mixed = pd.Series(["2024-01-05", "2024-01-05 14:30:00", "2024-01-05T14:30:00"])
print(pd.to_datetime(mixed, format="ISO8601"))format="ISO8601" accepts any ISO 8601 variant, including dates with and without times. format="mixed" infers the format for each element separately, like the old pandas 1.x behavior, so use it only when you have no better option. With "mixed", ambiguous strings such as 03/04/2024 can still be misread.
Cleaning before parsing
Placeholder text and stray whitespace are common causes of failures. Handle them before calling to_datetime, using the string cleaning tools from the earlier chapter:
import pandas as pd
raw = pd.Series([" 2024-01-05 ", "N/A", "2024-02-10", ""])
clean = raw.str.strip().replace({"N/A": None, "": None})
print(pd.to_datetime(clean, format="%Y-%m-%d"))Replacing known placeholders with None first means that errors="raise" still catches real surprises, because the expected missing values are already handled.
Time zones
A parsed column is time zone naive by default. It has no zone information, and pandas treats the times as plain wall-clock values. You have three common situations.
The strings include UTC offsets. Pass utc=True to convert everything to UTC in one step:
import pandas as pd
ts = pd.Series(["2024-03-10 08:00:00+01:00", "2024-03-10 08:00:00-05:00"])
utc = pd.to_datetime(ts, utc=True)
print(utc)
print(utc.dt.tz_convert("America/New_York"))The two values are five hours apart in UTC (07:00 and 13:00). Without utc=True, strings with different offsets produce an object column of Python datetime objects, because a single datetime64 dtype can hold only one zone. This is a frequent source of confusion, and a clue that you forgot utc=True.
The strings have no offset, but you know the zone. Parse first, then attach the zone:
import pandas as pd
naive = pd.to_datetime(pd.Series(["2024-03-10 08:00"]))
print(naive.dt.tz_localize("Europe/Paris"))tz_localize attaches a zone to naive values. tz_convert changes the zone of values that already have one. Calling tz_convert on a naive column raises an error, and calling tz_localize on an aware column does too.
Daylight saving gaps. A local time that never existed (clocks skipping forward) or that occurred twice (clocks going back) makes tz_localize raise an error. Pass nonexistent="shift_forward" or ambiguous="NaT" (or another documented option) to choose how to resolve them.
Numeric timestamps
Databases and APIs often store dates as numbers counting from the Unix epoch, 1970-01-01 UTC. Tell to_datetime the unit:
import pandas as pd
epoch = pd.Series([1704412800, 1704499200])
print(pd.to_datetime(epoch, unit="s"))The values become 2024-01-05 and 2024-01-06. Use unit="ms" for milliseconds, which JavaScript systems commonly produce. Choosing the wrong unit gives dates in 1970 or in the far future, so check the first few results against a date you know.
Building dates from separate columns
When year, month, and day live in separate columns, pass a DataFrame whose column names are recognized (year, month, day, and optionally hour, minute, second):
import pandas as pd
parts = pd.DataFrame({"year": [2024, 2024], "month": [1, 2], "day": [5, 10]})
print(pd.to_datetime(parts))This is more reliable than joining the pieces into a string and parsing that string.
Using the result
Once the column is datetime64, the .dt accessor gives you its parts:
import pandas as pd
d = pd.to_datetime(pd.Series(["2024-01-05", "2024-02-10"]))
print(d.dt.year.tolist())
print(d.dt.month.tolist())
print(d.dt.day_name().tolist())The output lists are [2024, 2024], [1, 2], and ['Friday', 'Saturday']. Subtracting two datetime columns gives a timedelta64 column, and .dt.days turns it into a number of days.
Finding the values that failed
With errors="coerce", failed values are indistinguishable from values that were already missing. Compare the parsed result with the original to separate the two:
import pandas as pd
raw = pd.Series(["2024-01-05", "05/01/2024", None, "bad"])
parsed = pd.to_datetime(raw, format="%Y-%m-%d", errors="coerce")
failed = raw[parsed.isna() & raw.notna()]
print(failed)The output shows index 1 (05/01/2024) and index 3 (bad). The None at index 2 is excluded because it was missing to begin with. Look at the failures, decide whether they need a second format, a cleaning step, or a manual fix, and then re-run the parse. A useful habit is to count them and stop when the count is unexpected:
n_failed = int((parsed.isna() & raw.notna()).sum())
print(f"{n_failed} values could not be parsed")Edge cases to know
- Out-of-range dates. The default nanosecond resolution covers roughly the years 1677 to 2262. Placeholder dates such as
9999-12-31fall outside it. In pandas 2.x,errors="raise"raisesOutOfBoundsDatetimeanderrors="coerce"returnsNaT. Check for sentinel dates before parsing. Newer pandas versions support coarser resolutions such as seconds, which widen the range, but the behavior depends on the version. - Two-digit years.
%ymaps 69 to 99 to the 1900s and 00 to 68 to the 2000s. Check that this suits your data. - Excel serial numbers. Excel stores dates as days since 1899-12-30. Use
pd.to_datetime(values, unit="D", origin="1899-12-30"). - Performance. Passing an explicit
formatis much faster than letting pandas guess, which matters on columns with millions of rows. - Repeated values. Parsing each unique string once is possible with
cache=True, which is the default and helps when the same dates repeat often.
Summary of the working model
- Inspect the column and look at a sample of values to learn their layouts.
- Clean whitespace and placeholders.
- Call
pd.to_datetimewith an explicitformat, plusutc=Trueorunit=when they apply. - Use
errors="coerce"only together with a check that lists the rows that failed. - Confirm the dtype with
df.dtypesand spot-check a few converted dates.
Exercise
A column holds the strings "07/08/2024" and "21/08/2024". You call pd.to_datetime(s) in pandas 2.x with no other arguments and get an error or NaT for the second value. Why does this happen, and what call fixes it?
Show answer
pandas 2.x guesses the format from the first value, "07/08/2024", as month/day/year, and applies it to every element. "21/08/2024" has no month 21, so it fails. The fix is to state the layout: pd.to_datetime(s, format="%d/%m/%Y"). Passing dayfirst=True also works for this data, but an explicit format is more reliable.
Exercise
Write code that converts the Series raw = pd.Series(["2024-05-01", "2024-13-01", None, "oops"]) with format "%Y-%m-%d" and prints only the original strings that failed to parse, excluding the missing value.
Show answer
parsed = pd.to_datetime(raw, format="%Y-%m-%d", errors="coerce") failed = raw[parsed.isna() & raw.notna()] print(failed) The output contains "2024-13-01" (month 13 is invalid) and "oops". The None is excluded by raw.notna().
Exercise
Timestamps like "2024-03-10 08:00:00+01:00" and "2024-03-10 08:00:00-05:00" are in one column. Without utc=True you get an object column instead of datetime64. Why, and how do you fix it?
Show answer
A datetime64 column can hold only one time zone, and these strings have different offsets, so pandas falls back to Python datetime objects in an object column. Pass utc=True to convert every value to UTC, then use .dt.tz_convert(zone) if you need another zone.