← 파이썬 강의 목록으로
⚙️
중급 (Intermediate)
datetime · random · pathlib · collections

4주차 — 표준 라이브러리

추가 설치 없이 import만으로 쓸 수 있는 4가지 핵심 표준 모듈 — 날짜·시간(datetime), 무작위(random), 경로(pathlib), Counter/defaultdict(collections).

datetimerandompathlibcollections
소요 시간
2시간
난이도
📊 중급
선수 조건
🎯 3주차
결과물
D-Day·로또·파일 통계 같은 도구 작성

이 강의에서 배우는 것

  • 1datetime 으로 날짜·시간을 다룬다
  • 2random 으로 무작위 값·샘플링
  • 3pathlib 으로 파일·폴더 경로
  • 4collections 의 Counter, defaultdict

1. datetime

python
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

python
import random

print(random.random())                  # 0.0 ~ 1.0
print(random.randint(1, 100))           # 1 ~ 100 정수
print(random.choice(["가위","바위","보"]))
print(random.sample(range(1, 46), 6))   # 로또
random.shuffle(my_list)                 # 제자리 섞기

3. pathlib

문자열보다 깔끔한 경로 다루기.

python
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)

# 폴더 내 파일 목록
for f in Path(".").glob("*.py"):
    print(f.name, f.stat().st_size)

4. collections

python
from collections import Counter, defaultdict, deque

# Counter — 빈도 계산 한 줄
text = "to be or not to be"
print(Counter(text.split()))    # {'to': 2, 'be': 2, ...}
print(Counter(text.split()).most_common(2))

# defaultdict — 키가 없으면 기본값
groups = defaultdict(list)
for name, age in [("A", 20), ("B", 25), ("C", 20)]:
    groups[age].append(name)
print(dict(groups))

# deque — 양방향 큐
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
print(dq)

5. 자주 하는 실수

  1. datetime vs date — datetime 은 시간까지, date 는 날짜만
  2. random.seed() 모름 — 같은 결과 재현하려면 random.seed(42) 처럼 시드 설정
  3. 경로 문자열 더하기 — "data" + "/" + "x" 보다 Path("data") / "x" 가 안전

6. FAQ

Q1. time 과 datetime 의 차이?

time 은 저수준(타임스탬프), datetime 은 고수준(객체). 보통 datetime 이면 충분.

Q2. os.path 와 pathlib 중 뭐?

신규 코드는 pathlib 권장. 더 OOP스럽고 가독성 좋음.

💻 예제 (examples)

실제로 실행해 결과를 확인할 수 있는 예제 코드입니다.

01_datetime.pydatetime / timedelta
CODE
from datetime import datetime, date, timedelta

now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))

today = date.today()
print("오늘:", today)
print("일주일 후:", today + timedelta(days=7))

birthday = date(2000, 5, 9)
print(f"태어난 후 {(today - birthday).days}일")
▶ 실행 결과
2026-05-10 14:32
오늘: 2026-05-10
일주일 후: 2026-05-17
태어난 후 9498일
02_random.pyrandom — 5가지 패턴
CODE
import random
random.seed(42)   # 재현 가능

print(random.random())
print(random.randint(1, 100))
print(random.choice(["가위", "바위", "보"]))
print(random.sample(range(1, 46), 6))

xs = [1, 2, 3, 4, 5]
random.shuffle(xs)
print(xs)
▶ 실행 결과
0.6394267984578837
82
바위
[8, 14, 21, 27, 36, 41]
[3, 1, 4, 5, 2]
03_pathlib.pypathlib — 경로/폴더/파일 한 번에
CODE
from pathlib import Path

p = Path("data") / "hello.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)

# 현재 폴더의 .py 파일 목록
for f in Path(".").glob("*.py"):
    print(f.name)
▶ 실행 결과
Hello!
True .txt hello.txt hello
01_datetime.py
02_random.py
03_pathlib.py
04_collections.py
04_collections.pyCounter / defaultdict / deque
CODE
from collections import Counter, defaultdict, deque

text = "to be or not to be that is the question to be"
c = Counter(text.split())
print(c.most_common(3))

groups = defaultdict(list)
for name, age in [("A", 20), ("B", 25), ("C", 20)]:
    groups[age].append(name)
print(dict(groups))

dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
print(dq)
▶ 실행 결과
[('to', 3), ('be', 3), ('or', 1)]
{20: ['A', 'C'], 25: ['B']}
deque([0, 1, 2, 3, 4])

📝 과제 (exercises)

직접 풀어보고, 막힐 때 정답을 펼쳐 비교해보세요.

과제 1

D-Day 계산기

목표: 기념일까지의 D-Day를 계산해 출력.

요구사항
  • 기념일 입력 (YYYY-MM-DD)
  • 오늘과의 차이 계산 후 D-N 또는 D+N 형태로 출력
입출력 예시
기념일: 2026-12-25
D-229
정답 코드 펼치기 / 접기
SOLUTION
from datetime import date

target = date.fromisoformat(input("기념일: "))
today = date.today()
diff = (target - today).days

if diff > 0:
    print(f"D-{diff}")
elif diff < 0:
    print(f"D+{-diff}")
else:
    print("D-DAY!")
▶ 실행 결과
기념일: 2026-12-25
D-229
과제 2

폴더 내 .txt 파일 크기 출력

목표: 현재 폴더의 모든 .txt 파일 이름과 크기를 한 줄씩.

요구사항
  • pathlib.Path(".").glob("*.txt") 사용
  • f.stat().st_size 로 크기
입출력 예시
notes.txt: 1234 bytes
todo.txt: 567 bytes
정답 코드 펼치기 / 접기
SOLUTION
from pathlib import Path

for f in Path(".").glob("*.txt"):
    print(f"{f.name}: {f.stat().st_size} bytes")
▶ 실행 결과
notes.txt: 1234 bytes
todo.txt: 567 bytes
과제 3

단어 빈도 Top 5 (Counter)

목표: Counter로 가장 자주 등장한 단어 5개.

요구사항
  • text.split() + Counter + most_common(5)
입출력 예시
apple: 5
banana: 4
cherry: 3
date: 2
egg: 2
정답 코드 펼치기 / 접기
SOLUTION
from collections import Counter

text = "apple banana apple cherry banana apple cherry banana apple cherry apple date egg banana date egg"
words = text.split()

for word, n in Counter(words).most_common(5):
    print(f"{word}: {n}")
▶ 실행 결과
apple: 5
banana: 4
cherry: 3
date: 2
egg: 2
예제 코드 / 강의 자료

전체 강의 자료와 예제 코드는 GitHub에서 자유롭게 받아볼 수 있습니다.

GitHub에서 보기 ↗