strptime Parses Dates With Format Codes
datetime.strptime maps format directives onto a fixed string layout and raises ValueError on any mismatch, giving strict parsing for inbound date fields.
Code
from datetime import datetime, timedelta
stamp = "2026-11-14T09:30:00"
deploy = datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%S")
print("parsed:", deploy.year, deploy.month, deploy.day, deploy.hour)
# the format must match the string character for character: a wrong order raises ValueError
try:
datetime.strptime("14/11/2026", "%Y-%m-%d")
except ValueError as exc:
print("rejected:", exc)
# after parsing you are in datetime land: timedelta arithmetic plus strftime for the reverse direction
deadline = deploy + timedelta(days=2, hours=6)
print("deadline:", deadline.strftime("%Y-%m-%d %H:%M"))
print("gap hours:", (deadline - deploy).total_seconds() / 3600)How it works
Module-level bindings hold the data — stamp, deploy, deadline — with no function scope in between.
Putting it to use
Running the file prints labeled results such as parsed:, rejected:, deadline: — each operation’s effect is visible in the output.
Core lines
except ValueError as exc:
print("rejected:", exc)
Interactive Tools for This Topic
Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.Cron Next Runs CalculatorCompute the next scheduled run times for a standard five-field cron expression, supporting ranges, lists, steps, and day-of-week naming semantics.ISO Week CalculatorFind the ISO 8601 week number, ISO week-year, week start and end dates, and day of year for any calendar date, with strict date validation.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. Every import resolves inside the standard library — `datetime`. Its state lives in module-level bindings: `stamp`, `deploy`, `deadline`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.