53
Date & Time
Date & Time (datetime): The Standard Way to Handle Time Data
What might confuse you right now
"Isn't time just a string? Why make it an object?"
Strings can display time, but they can't reliably compute with it. Comparisons, arithmetic, and format conversions all need datetime objects.
One-line definition
datetime provides time creation, parsing, formatting, and arithmetic.
Real-life analogy
A handwritten calendar can be read but can't do math. A digital calendar auto-reminds and calculates.
Minimal runnable example
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
deadline = now + timedelta(days=7)
print(deadline.strftime("%Y-%m-%d"))
String to datetime
dt = datetime.strptime("2026-02-11 09:30", "%Y-%m-%d %H:%M")
print(dt)
Quick quiz (5 min)
- Print the current time, formatted.
- Calculate the date 30 days from now.
- Write a function that returns how many days remain until a deadline.
Quiz answer guidelines & grading criteria
- Answer direction: working code that covers core conditions and edge inputs from the prompt.
- Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
- Criterion 2 (Readability): Clear variable names, no excessive nesting.
- Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.
Transfer task (homework)
Build a "task deadline reminder": input a due date, output remaining days and status.
Acceptance criteria
You can independently:
- Parse and format time strings
- Use
timedeltafor time arithmetic - Avoid comparing time via raw strings
Common errors & debugging steps (beginner edition)
- Can't understand the error: read the last line for the error type (e.g.,
TypeError,NameError), then trace back to the relevant code line. - Not sure about a variable's value: temporarily add
print(variable, type(variable))at key points to verify data matches expectations. - Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.
Common misconceptions
- Misconception: Comparing time strings directly works fine.
- Reality: Convert to datetime first, then compare.