Sub topic 2
Parsing text into datetimes with to_datetime
This chapter assumes you can create and index a pandas Series or DataFrame, filter rows with boolean masks, and use Python's datetime module. It covers pd.to_datetime, the function that turns text into real datetime values. Everything later in this tutorial (the .dt accessor, time-based indexing, resampling) depends on having a proper datetime column first.
Why parsing comes first
Dates usually arrive as text. A CSV file has no date type, so pandas reads a column like 2024-03-01 09:30 as object dtype, which holds Python strings. Strings sort alphabetically, can't be subtracted, and have no .dt accessor.
pd.to_datetime converts such a column to datetime64, pandas' native timestamp type. The result supports date arithmetic, calendar extraction, and time-based selection.
The basic call with an explicit format
The most reliable way to parse is to tell pandas the exact layout of your strings with the format argument.
import pandas as pd
df = pd.DataFrame({
"when": ["2024-03-01 09:30", "2024-03-02 14:45", "2024-03-05 08:00"],
"amount": [10, 25, 40],
})
df["when"] = pd.to_datetime(df["when"], format="%Y-%m-%d %H:%M")
print(df.dtypes)The when column now reports a dtype of datetime64[ns]. The ns means nanosecond resolution. Depending on your pandas version, the unit may differ, but the column is a datetime type either way.
The format string uses strftime codes. Each code stands for one piece of the date, and everything else must match literally.
| Code | Meaning | Example |
|---|---|---|
| `%Y` | 4-digit year | 2024 |
| `%y` | 2-digit year | 24 |
| `%m` | month number | 03 |
| `%b` / `%B` | month name, short / full | Mar / March |
| `%d` | day of month | 05 |
| `%H` / `%I` | hour, 24-hour / 12-hour | 14 / 02 |
| `%p` | AM or PM | PM |
| `%M` / `%S` | minute / second | 45 / 00 |
| `%f` | fractional seconds | 123456 |
| `%z` | UTC offset | +0100 |
A string that doesn't fit the format is an error (or a NaT, see below). A format of "%Y-%m-%d" fails on "2024-03-01 09:30" because of the extra time portion.
What happens when you omit the format
You can call pd.to_datetime(series) with no format. In pandas 2.0 and later, pandas guesses a format from the first non-missing value and applies it to the whole column. This is fast and works well for clean, uniform data.
The risk is inconsistent data. If row 1 looks like 2024-01-05 and row 500 looks like 5 Jan 2024, the guessed format fails on row 500. You have three options:
- Fix the source so the data is uniform. This is the best option.
- Pass
format="ISO8601"if every string follows an ISO 8601 layout, even with varying precision (some with times, some without). - Pass
format="mixed"to parse each element on its own. It handles messy data but is slower and more likely to guess wrong on ambiguous values.
Older pandas versions (before 2.0) guessed per element by default, which silently mixed formats. If you maintain older code, check which version you're on.
Invalid values: the errors argument
By default, one unparseable string raises a ValueError and the whole call fails. The errors argument changes that.
errors="raise"is the default. It stops at the first bad value.errors="coerce"turns each bad value intoNaT("Not a Time"), the datetime version ofNaN.
bad = pd.Series(["2024-01-05", "not a date"])
parsed = pd.to_datetime(bad, errors="coerce")
print(parsed)
print(parsed.isna())
print(pd.to_datetime("03/04/2024", dayfirst=True))The first print shows 2024-01-05 and NaT. The second shows False then True. The last line prints 2024-04-03 00:00:00, which is the next section's topic.
coerce is convenient but hides problems. A typo and a genuinely missing value both become NaT, so you can no longer tell them apart. A safer pattern is to coerce, then compare against the original to see which rows failed:
raw = pd.Series(["2024-01-05", "2024-13-40", None, "garbage"])
parsed = pd.to_datetime(raw, format="%Y-%m-%d", errors="coerce")
failed = parsed.isna() & raw.notna()
print(raw[failed])This prints the two strings 2024-13-40 and garbage. The None row is excluded because it was already missing in the input. The next chapter covers NaT handling in more detail.
Ambiguous dates and dayfirst
The string 03/04/2024 could be 4 March or 3 April. With no hint, pandas assumes month first, the US convention, and reads it as 4 March 2024.
Passing dayfirst=True flips that to day first, giving 3 April 2024. The reverse flag, yearfirst=True, treats the first number as the year.
Treat dayfirst as a weak hint, not a guarantee. When a string can't be read day-first (for example 03/25/2024), pandas may quietly fall back to month-first for that element and emit a warning. The robust fix is an explicit format such as format="%d/%m/%Y". That fails loudly on values that don't fit, instead of guessing.
Parsing numbers and column parts
Strings are not the only input. to_datetime also accepts numbers and even DataFrame columns.
Numbers are read as offsets from the Unix epoch (1970-01-01 UTC), with the unit argument saying whether they are seconds, milliseconds, and so on:
epoch = pd.Series([1700000000, 1700086400])
print(pd.to_datetime(epoch, unit="s"))The first value is 2023-11-14 22:13:20 and the second is exactly one day later. Using the wrong unit is a common error. Milliseconds read as seconds land thousands of years in the future and typically raise an out-of-bounds error.
When year, month, and day live in separate columns, pass a DataFrame whose columns are named year, month, and day. Optional columns hour, minute, and second are also recognized:
parts = pd.DataFrame({"year": [2024, 2024], "month": [3, 4], "day": [1, 15]})
print(pd.to_datetime(parts))Parsing time zones with utc=True
If strings include a UTC offset, such as 2024-03-01 09:00+01:00, pandas keeps it. When every string has the same offset, you get a time-zone-aware column. When the offsets differ, pandas can't represent them in one datetime64 column. Depending on version, you get an object column of Python datetimes or a warning or error.
The fix is utc=True, which converts every value to UTC and returns a single aware column:
mixed = ["2024-03-01 09:00+01:00", "2024-03-01 09:00+05:00"]
print(pd.to_datetime(mixed, utc=True))The results are 2024-03-01 08:00:00+00:00 and 2024-03-01 04:00:00+00:00. You can convert to a local zone afterward. Time zones get their own chapter later in this tutorial.
For strings that have no offset at all, utc=True does something different: it labels them as UTC, assuming that is what they mean. Be sure that assumption is true before using it.
Parsing while reading files
For CSV files, you can parse during loading with parse_dates and, in pandas 2.0 and later, date_format:
import io
csv_text = "when,amount\n2024-03-01 09:30,10\n2024-03-02 14:45,25\n"
df = pd.read_csv(
io.StringIO(csv_text),
parse_dates=["when"],
date_format="%Y-%m-%d %H:%M",
)
print(df.dtypes)This is equivalent to reading first and calling to_datetime afterward. Parsing after the read gives you more control, because you can inspect the raw strings and any NaT results before committing.
Performance and limits
Two practical points matter on large data.
- Format speed. An explicit
formatis much faster than guessing, because pandas can use a fast path with a known layout. On millions of rows the difference is substantial. If many values repeat, as with daily timestamps,cache=True(the default for larger inputs) parses each unique string once. - Range limits. With nanosecond resolution, the representable range is roughly the years 1678 to 2262. A string like
3000-01-01raisesOutOfBoundsDatetimein pandas 2.x. Witherrors="coerce"it becomesNaT. Check your version's documentation if you work with historical or far-future dates, because newer versions support other resolutions.
A parsing checklist
- Check the raw strings first:
df["when"].head()anddf["when"].str.len().value_counts()reveal inconsistent lengths quickly. - Pass an explicit
formatwhenever you know the layout. - Leave
errorsat"raise"while developing so problems are visible. - If you coerce, count the new
NaTvalues and compare to the originals. - Confirm the result with
df["when"].dtype. It should bedatetime64[...], notobject.
Exercise
A column contains the strings "25/12/2024", "01/02/2024", and "31/01/2024". Write the call that parses it correctly, and explain why pd.to_datetime(col) alone is risky here.
Show answer
Use pd.to_datetime(col, format="%d/%m/%Y"). Without a format, pandas assumes month-first. "25/12/2024" and "31/01/2024" can't be month-first, so pandas may fall back for those elements, while "01/02/2024" is silently read as 2 January instead of 1 February. The result mixes conventions with no error. The explicit format reads every value day-first and raises on anything that doesn't fit.
Exercise
You parse a column with errors="coerce" and get 12 NaT values. How do you find out which of them came from bad text and which were already missing in the input?
Show answer
Compare against the raw column: failed = parsed.isna() & raw.notna(). Rows where the result is NaT but the original was not null failed to parse. raw[failed] shows the offending strings. The remaining NaT rows were already missing.
Exercise
You receive the strings "2024-03-01 09:00+01:00" and "2024-03-01 09:00+05:00". Which argument makes to_datetime return one consistent time-zone-aware column, and what UTC times does it produce?
Show answer
Pass utc=True. It converts both values to UTC, giving 2024-03-01 08:00:00+00:00 and 2024-03-01 04:00:00+00:00.