Level: Intermediate | Prerequisite: Week 3 (Module/Package)
Learning Goals
- Handle date and time with
datetime - Random values and sampling with
random - File and folder paths with
pathlib Counter,defaultdictofcollections
The standard library can be imported directly without additional installation.
1. datetime
from datetime import datetime, date, timedelta
now = datetime.now()
print(now)
print(now.strftime("%Y-%m-%d %H:%M"))
today = date.today()
birthday = date(2000, 5, 9)
days_lived = (today - birthday).days
next_week = now + timedelta(days=7)
2. random
import random
print(random.random()) # 0.0 ~ 1.0
print(random.randint(1, 100)) #Integers 1 ~ 100
print(random.choice(["Scissors","Rock","Paper"]))
print(random.sample(range(1, 46), 6)) #Lotto
random.shuffle(my_list) #In-place shuffling
3. pathlib
Handle paths more cleanly than strings.
from pathlib import Path
p = Path("data") / "report.txt" # data/report.txt
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("hello", encoding="utf-8")
print(p.read_text(encoding="utf-8"))
print(p.exists(), p.suffix, p.name, p.stem)
#List of files in the folder
for f in Path(".").glob("*.py"):
print(f.name, f.stat().st_size)
4. collections
from collections import Counter, defaultdict, deque
#Counter — Frequency count, one line
text = "to be or not to be"
print(Counter(text.split())) # {'to': 2, 'be': 2, ...}
print(Counter(text.split()).most_common(2))
#defaultdict — Default value if key is missing
groups = defaultdict(list)
for name, age in [("A", 20), ("B", 25), ("C", 20)]:
groups[age].append(name)
print(dict(groups))
#deque — Double-ended queue
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
print(dq)
Key Examples (examples/)
| File | Content |
|---|---|
01_datetime.py |
Date/Time |
02_random.py |
Random |
03_pathlib.py |
Path |
04_collections.py |
Counter, defaultdict |
⚠️ Common Mistakes
datetimevsdate—datetimeincludes time,dateonly date.- Don't know
random.seed()— Set a seed likerandom.seed(42)to reproduce the same results. - Adding path strings —
Path("data") / "x"is safer than"data" + "/" + "x".
❓ FAQ
Q1. Difference between time and datetime?
A. time is low-level (timestamp), datetime is high-level (object). Usually, datetime is enough.
Q2. Which to use, os.path or pathlib?
A. For new code, pathlib is recommended. More OOP-like and readable.
📝 Exercises (exercises/)
exercise1.md— D-Day calculatorexercise2.md— Print sizes of .txt files in a folderexercise3.md— Top 5 word frequencies (Counter)
Next Week
Week 5. Exception Handling