stdlib Deep Dive & pip
json, datetime, pathlib, requests, venv, and pip
Skills taught: python.json, python.datetime, python.pathlib, python.pip, python.venv, python.requests
json — working with APIs and config
import json
# Python dict → JSON string
data = {
'name': 'Prashant',
'scores': [95, 82, 78],
'active': True,
'email': None
}
json_str = json.dumps(data) # compact
json_pretty = json.dumps(data, indent=2) # readable
print(json_pretty)
# {
# "name": "Prashant",
# "scores": [95, 82, 78],
# "active": true,
# "email": null
# }
# JSON string → Python dict
parsed = json.loads(json_str)
print(parsed['name']) # Prashant
print(type(parsed['active'])) # <class 'bool'>
# Read/write JSON files
with open('data.json', 'w') as f:
json.dump(data, f, indent=2) # write
with open('data.json') as f:
loaded = json.load(f) # read
# Type mappings
# Python → JSON
# dict → object {}
# list → array []
# str → string ""
# int → number
# float → number
# True → true
# False → false
# None → null
datetime — working with dates and times
from datetime import datetime, timedelta, date
# Current date and time
now = datetime.now()
print(now) # 2026-09-20 14:30:00.123456
print(now.year, now.month, now.day)
print(now.hour, now.minute, now.second)
# Date arithmetic
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
print(tomorrow.date()) # 2026-09-21
print(last_week.date()) # 2026-09-13
# Format: datetime → string
formatted = now.strftime('%Y-%m-%d %H:%M')
print(formatted) # '2026-09-20 14:30'
# Parse: string → datetime
dt = datetime.strptime('20-09-2026', '%d-%m-%Y')
print(dt.year) # 2026
# ISO format (for APIs)
iso = now.isoformat() # '2026-09-20T14:30:00.123456'
back = datetime.fromisoformat(iso) # parse back
# Just a date (no time)
today = date.today()
birthday = date(1998, 6, 15)
age_days = (today - birthday).days
print(f'{age_days} days old')
pip and virtual environments
# Create a virtual environment
python -m venv venv
# Activate it
# Windows:
venv\Scripts\activate
# Mac/Linux:
source venv/bin/activate
# Your prompt now shows (venv)
# Install packages
pip install requests
pip install requests==2.31.0 # specific version
pip install "requests>=2.28" # minimum version
# See what's installed
pip list
pip show requests
# Save dependencies for sharing
pip freeze > requirements.txt # saves exact versions
# Install from requirements file
pip install -r requirements.txt
# Deactivate when done
deactivate
requests — HTTP made easy
import requests
# GET request
response = requests.get('https://api.github.com/users/torvalds')
print(response.status_code) # 200
print(response.headers['content-type']) # application/json
data = response.json() # parse JSON response
print(data['name']) # Linus Torvalds
print(data['public_repos']) # number of repos
# Error handling
try:
resp = requests.get('https://api.example.com/data', timeout=5)
resp.raise_for_status() # raises HTTPError if 4xx/5xx
data = resp.json()
except requests.Timeout:
print('Request timed out')
except requests.HTTPError as e:
print(f'HTTP Error: {e}')
# POST request with JSON body
payload = {'username': 'prashant', 'email': 'p@example.com'}
resp = requests.post(
'https://httpbin.org/post',
json=payload, # auto-sets Content-Type: application/json
headers={'Authorization': 'Bearer my-token'}
)
print(resp.status_code)
Frequently Asked Questions
What is the difference between json.dump() and json.dumps()?
json.dumps() converts Python → JSON string (in memory). json.dump() writes Python → JSON directly to a file object. The 's' stands for 'string'. Same pattern: json.loads() parses a JSON string, json.load() reads from a file.
Do I need to install requests? It's not in the standard library?
Correct — requests is a third-party package. Install with: pip install requests. Python 3.11+ includes urllib.request in stdlib, but requests is far more ergonomic. Python 3.12's httpx is another modern option.