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.

PythonData Integrity

Code

pythonsnippet
16 lines
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

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`.