Datetime Module
Python's datetime module provides classes for manipulating dates and times. Essential for timestamping, scheduling, and time calculations.
💻 Date & Time Basics
from datetime import datetime, date, time, timedelta
# Current date and time
now = datetime.now()
print(now) # 2025-11-15 14:30:45.123456
# Current date only
today = date.today()
print(today) # 2025-11-15
# Create specific date
birthday = date(1990, 5, 15)
print(birthday) # 1990-05-15
# Create specific datetime
event = datetime(2025, 12, 31, 23, 59, 59)
print(event) # 2025-12-31 23:59:59
# Time only
meeting = time(14, 30, 0)
print(meeting) # 14:30:00🔧 Date Arithmetic
# Timedelta (time difference)
one_week = timedelta(days=7)
next_week = today + one_week
print(next_week)
# Calculate difference
birthday = date(1990, 5, 15)
age_days = today - birthday
print(age_days.days) # Days alive
# Add/subtract time
now = datetime.now()
future = now + timedelta(hours=2, minutes=30)
past = now - timedelta(days=1)
# Compare dates
if today > birthday:
print("Birthday has passed")
# Get components
print(now.year) # 2025
print(now.month) # 11
print(now.day) # 15
print(now.hour) # 14
print(now.weekday()) # 0=Monday, 6=Sunday📊 Formatting & Parsing
# Format datetime to string
now = datetime.now()
formatted = now.strftime('%Y-%m-%d %H:%M:%S')
print(formatted) # 2025-11-15 14:30:45
# Common format codes
print(now.strftime('%B %d, %Y')) # November 15, 2025
print(now.strftime('%m/%d/%Y')) # 11/15/2025
print(now.strftime('%I:%M %p')) # 02:30 PM
print(now.strftime('%A, %B %d')) # Friday, November 15
# Parse string to datetime
date_str = '2025-11-15 14:30:45'
parsed = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
print(parsed)
# ISO format
iso = now.isoformat()
print(iso) # 2025-11-15T14:30:45.123456
# Timestamp (Unix epoch)
timestamp = now.timestamp()
from_timestamp = datetime.fromtimestamp(timestamp)🎯 Key Takeaways
- datetime.now(): Current date and time
- date.today(): Current date
- timedelta: Represent time differences
- strftime(): Format datetime to string
- strptime(): Parse string to datetime
- Arithmetic: Add/subtract dates with +/-
- Common codes: %Y(year), %m(month), %d(day), %H(hour), %M(minute)