Skip to content

Parsing Datetime Strings in Python: A Practical Tool-Choice Guide

A date string in a scraped page, log line, API payload or CSV rarely arrives in one tidy shape. Some values are strict ISO timestamps, some are hand-typed like "15th June 2026", and some are relative phrases such as "2 days ago" or "il y a 3 jours". Python offers several parsers, and the useful question is not which one is best in general but which one fits the string shape in front of you. This guide walks through the five main options, the settings that resolve ambiguity, and the failure modes that matter when you move from a few test strings to thousands of records.

Match the parser to the string shape

The trade-off is straightforward: the stricter the parser, the faster it runs, and the less it can guess. If you know the exact layout, a format-driven parser is the efficient choice. If the layout varies but stays in familiar Western conventions, a format-detecting parser saves effort. If the values are human-written, relative or in another language, you need a library built for that messiness. And if the dates sit in a table column, a vectorized call handles the whole column at once.

A short decision checklist:

  • Exact layout known and stable → datetime.strptime() with a format string.
  • Value is ISO 8601 → datetime.fromisoformat() first.
  • Layout unknown but English/Western → dateutil.parser.parse().
  • Relative, multilingual, incomplete or scraped free text → dateparser.parse().
  • Whole column in a DataFrame or CSV → pandas.to_datetime().
  • Comparing or storing across zones → decide naive vs timezone-aware before parsing.

The comparison table below summarizes the same trade-offs by method, format requirement, speed and relative/multilingual support.

Known formats: datetime.strptime()

strptime() takes the string plus a format template built from percent codes. Characters outside the codes must appear literally, so hyphens, slashes and spaces in the template have to match the input exactly. A mismatch raises ValueError rather than returning a partial result. The function is the inverse of strftime(), which turns a datetime back into text.

The format-code table below lists the codes you will reach for most often, including the two-digit and four-digit year codes and the numeric versus named timezone codes.

Reading strptime failures correctly

Most strptime errors come from a template that does not describe the whole string. Three recurring cases are worth separating:

  • Year width: %y expects two digits, %Y expects four. Feeding a two-digit year to %Y fails.
  • Leftover text: if the template stops before the input does, Python reports unconverted data remains. A date-only template applied to a date-plus-time string is the classic example.
  • Named zones: %Z is unreliable beyond UTC and GMT and the local machine zone. Numeric offsets via %z are the dependable route, and named zones from scraped pages are better handled by dateparser.

When a template is wrong, the fix is to widen or correct the template, not to catch and ignore the error. The code modules accompanying this page show each failure and its corrected template.

ISO 8601 values: datetime.fromisoformat()

ISO strings are the common shape in JSON APIs and structured data blocks, and fromisoformat() handles them without a template. From Python 3.11 onward it accepts most valid ISO 8601 forms, including a trailing Z and numeric offsets; earlier versions were limited to strings that isoformat() itself would produce. The examples accompanying this page were run on Python 3.14 and should behave the same from 3.11.

It accepts compact and extended date forms, week dates, date-time with T or a space, optional seconds and microseconds, and offsets. If a value is genuinely ISO, try this before reaching for a template.

Unknown Western formats: dateutil.parser.parse()

dateutil is a third-party package, installed with pip install python-dateutil or uv add python-dateutil. Its parser detects common Western layouts without a template, which suits manually entered or inconsistently formatted dates. It does not handle relative phrases, non-English month names or ambiguous named zones such as EST and PST.

Ambiguity appears when three two-digit numbers are separated by punctuation. The default reads month first when the first number is 12 or less; dayfirst=True and yearfirst=True switch the reading when the page context tells you the local convention. The same flags work across slash, dot, hyphen and space separators.

Messy, relative and multilingual values: dateparser

dateparser covers the shapes the standard library and dateutil leave behind: relative phrases, more than 200 language locales, incomplete dates and values that are not dates at all. Install it with pip install dateparser or uv add dateparser. Its parse() returns a datetime on success and None on failure, so check the result rather than expecting an exception.

A worked example from the supplied evidence: a list containing a clean ISO date, "5 days ago", a Spanish date, a French relative phrase, an ambiguous numeric date and "Unknown, TBA" parses to real datetimes for the first five and None for the last. That None is the signal to route the row to a review queue rather than to crash the pipeline.

dateparser settings that resolve ambiguity

Several settings change how dateparser interprets a value. Treat them as a control map:

  • DATE_ORDER: "MDY" (default), "DMY" or "YMD" for three-number strings. Set it from the source site's locale.
  • PREFER_DATES_FROM: "past" (default) or "future" for phrases such as "two years" that could point either way.
  • RETURN_AS_TIMEZONE_AWARE: True to get aware datetimes instead of naive ones.
  • TIMEZONE: attach a zone when the string itself carries none.
  • PREFER_DAY_OF_MONTH: "first", "last" or "current" for incomplete dates such as "December 2023".

A named zone in the string, such as PST, is resolved when aware output is requested. The code modules accompanying this page show each setting in use.

Pulling a date out of free text: search_dates()

search_dates() scans a longer passage and returns a list of matches, each pairing the matched text with the parsed datetime. It works across languages, which makes it useful when a date is buried in a sentence rather than isolated in a field. It is slower and its coverage is limited, so reserve it for cases where the date cannot be isolated first. The examples accompanying this page show an English and a Spanish sentence returning the same calendar date.

Whole columns: pandas.to_datetime()

When dates arrive as a column in a DataFrame or CSV, pandas.to_datetime() converts the whole column in one call. Supplying a format makes it faster because pandas does not have to infer each value. The errors parameter controls failure handling: the default raise stops on the first bad value, while coerce turns unparseable entries into NaT and leaves valid ones as datetimes.

The supplied example uses a small DataFrame with mixed formats and one "N/A" entry. With errors="coerce" and format="mixed", the four real dates become datetimes and the missing value becomes NaT, which is the shape you want before downstream filtering.

Speed at scale

The parsers stack on each other: dateparser builds on dateutil, and dateutil builds on the low-level standard methods while adding detection. That layering explains the speed order. In the supplied benchmark, 10,000 yyyy-mm-dd strings were parsed with each method and timed with timeit over three repetitions. Relative to fromisoformat at 1.0, strptime and pandas.to_datetime measured about 43, dateutil about 167, and dateparser about 13,786. Those are dated captured figures from one machine and one input shape, not a guarantee for your data; re-measure if the volume matters.

The practical rule: use the strictest parser the data allows. If the format is uniform, detect it once and use strptime rather than paying the detection cost on every row.

A scraping pipeline that survives real dates

Scraped dates are written for humans, so they carry local conventions, relative phrasing and missing zones. Parse them as early as possible, and decide up front whether the pipeline stores naive or aware datetimes. Mixing the two raises TypeError when you compare them. Normalizing to UTC before comparison avoids that.

A second trap appears at storage time: datetime objects are not JSON serializable. Convert them with isoformat() before dumping. A workable order is: fetch the page, pick the parser from the table above, normalize to UTC or parse as aware, then serialize as ISO strings.

The code modules accompanying this page show the TypeError from mixing naive and aware values, the UTC normalization that fixes it, and the JSON error with its isoformat() fix.

Failure map: which error means what

The four failure signals point at different problems, and confusing them wastes debugging time:

  • ValueError from strptime: the template does not match the string. Fix the template.
  • None from dateparser.parse(): the string was not recognized as a date. Route it to review.
  • NaT from pandas with errors="coerce": the value was unparseable in a column operation. Filter or fill it.
  • TypeError from comparing datetimes: one value is naive and the other aware. Normalize both.
  • TypeError from json.dumps: a datetime object reached the serializer. Convert with isoformat().

Keeping these separate makes the pipeline's logs readable and the fixes obvious.

Python date parser comparison
MethodBest forNeeds a format string?SpeedHandles relative / multilingual?
datetime.strptime()Known fixed formatsyesfastestno
datetime.fromisoformat()ISO 8601 onlynofastestno
dateutil.parser.parse()unknown Western formatsnomediumno
dateparser.parse()messy, relative, multilingual, scrapednoslowestyes
pandas.to_datetime()a whole column or seriesoptionalfast on columnspartial

Speed labels are relative rankings from the supplied comparison, not absolute timings.

Frequently asked questions

How do I parse a datetime string in Python without knowing the format?

dateutil.parser.parse handles standard Western layouts in English without a template. For relative phrases, non-English dates, or messy and incomplete values, use dateparser.parse. Both detect the format and return a datetime object, but dateparser returns None on failure rather than raising.

How do I parse a datetime string with a timezone in Python?

For ISO offsets such as +02:00, datetime.fromisoformat() is the direct route. For numeric offsets in a custom layout, use strptime() with %z. Named zones such as EST or PST are best handled by dateparser, since the standard functions are unreliable there. If you know the zone but the string does not carry it, attach it after parsing.

What is the difference between strptime() and fromisoformat()?

strptime() needs you to supply a format template; fromisoformat() assumes an ISO 8601 string. The ISO route is faster and, from Python 3.11, accepts almost any valid ISO 8601 value. Try it first for ISO dates and fall back to strptime() only when the value is not ISO.

How do I parse a string like "2 days ago" in Python?

Relative phrases are handled by dateparser, including non-English forms such as "il y a 3 jours". strptime and dateutil do not handle them. Use PREFER_DATES_FROM to choose past or future when the phrase is ambiguous.

How do I fix "ValueError: time data does not match format"?

The template does not describe the input. Check two-digit versus four-digit year codes, and make sure the template covers the whole string so no unconverted data remains. For named zones, remember that %Z is reliable only for UTC and GMT, so route those values to dateparser.

How do I convert a parsed datetime back to a yyyy-mm-dd string?

Call strftime("%Y-%m-%d") on the datetime object. It is the inverse of strptime, which builds a datetime from text.

Common strptime format codes
CodeMeaningExample
%YYear in 4 digits2026
%yYear, last 2 digits26
%mMonth number06
%bMonth name abbreviatedJun
%BMonth name in fullJune
%dDay of month15
%HHour in 24-hr format17
%IHour in 12-hr format5
%MMinute45
%SSecond56
%fMicrosecond (6 digits)123456
%pAM/PMPM
%ZNamed timezone (unreliable support)GMT
%zTimezone (numeric UTC offset)+02:00

Codes are case-sensitive; literal separators in the template must match the input.