datetime.strptime('2024-01-15', '%Y-%m-%d')
Standard Library Idioms

Meaning

Parses a date‑time string into a datetime.datetime object using a specified format string. It eliminates the need for manual string slicing and reduces errors when converting user‑input or log timestamps. You reach for it when you have a date string that matches a known pattern and need to perform date arithmetic or storage.

Primary Function

Date parsing

Communicative Purpose

Enables reliable conversion of formatted date strings into datetime objects for further processing.

Pattern

datetime.strptime(date_string, format_string)

Core Structure

datetime.strptime(..., ...)

Função primária

Date parsing

Propósito comunicativo

Enables reliable conversion of formatted date strings into datetime objects for further processing.

Situações de gatilho

Web scraping: extracting publication dates from HTML meta tags; Data pipelines: converting CSV date columns to datetime objects for analysis; Logging: parsing timestamps from log files into datetime objects.

Contextos

Python data analysis, web backends, automation scripts, ETL pipelines

Padrão

datetime.strptime(date_string, format_string)

Estrutura central

datetime.strptime(..., ...)

Slots de substituição

date_string: str, format_string: str

Colocados típicos

  • Often paired with try/except ValueError for invalid formats
  • used with datetime.datetime objects
  • combined with strftime for reverse formatting.

Substituições comuns

  • dateutil.parser.parse (more flexible but heavier)
  • pandas.to_datetime (vectorized parsing for Series)
  • datetime.fromisoformat (ISO‑8601 only
  • faster).

Erros comuns

Swapping the arguments (format first, date string second) → TypeError: strptime() argument 1 must be str, not _datetime.datetime; Using incorrect format directives (e.g., %M for month instead of %m) → ValueError: time data does not match format; Passing a non‑string (e.g., datetime object) as the first argument → AttributeError: 'datetime.datetime' object has no attribute 'strptime'; Forgetting to import the datetime module → NameError: name 'datetime' is not defined; Including leading/trailing whitespace in the date string → ValueError: unconverted data remains.

Similar / contraste

datetime.strftime (formats datetime → string); dateutil.parser.parse (flexible parsing without format string); datetime.fromisoformat (ISO‑8601 only parsing).

Interferências

Coming from JavaScript: assuming Date.parse works like strptime → Python requires an explicit format string; Coming from SQL: expecting %Y-%m-%d to be interpreted as a date literal → the format string must be passed as an argument and the input must be a string.

Família do chunk

  • datetime.strftime
  • datetime.fromisoformat
  • dateutil.parser.parse

Nuance

Do not use when locale‑aware parsing is needed (e.g., month names in non‑English locales); consider babel or dateutil instead.; Performance impact is minimal for occasional calls, but parsing in tight loops can become a bottleneck; consider caching results or using vectorized libraries like pandas.; Boundary conditions: the format must match exactly, extra whitespace causes ValueError, and two‑digit years (%y) interpret 00‑68 as 2000‑2068 and 69‑99 as 1969‑1999.

Efeito pragmático

Enables reliable conversion of user‑supplied date strings into datetime objects for arithmetic, storage, or display, preventing bugs caused by manual string slicing or incorrect assumptions about format.

Dica de memória

Think of strptime as a translator that turns a date written in human language into a computer’s internal clock, but only if you hand it the exact dictionary.

Nota

The format directives follow the same specification as strftime; see the Python documentation for a full list.

Upgrade path

Use dateutil.parser.parse for locale‑aware, flexible date parsing.

Frequência: HighFormulaicidade: Semi-fixedPrioridade de aquisição: Active recallPrioridade de output: BothTag de espaçamento: Medium-term

Log in to save chunks.