Date & Time
Work with dates, times, and timedeltas using Python's datetime module
Working with Dates
- datetime module provides date and time classes
- date class represents calendar dates
- datetime class combines date and time
- Can create, format, and manipulate dates
from datetime import date, datetime
# Current date
today = date.today()
print(f"Today: {today}")
# Create specific date
birthday = date(1990, 5, 15)
print(f"Birthday: {birthday}")
# Date components
print(f"Year: {today.year}")
print(f"Month: {today.month}")
print(f"Day: {today.day}")
# Current datetime
now = datetime.now()
print(f"Now: {now}")
Working with Time
- time class represents time of day
- datetime includes both date and time
- Can extract hours, minutes, seconds
- Supports microseconds for precision
from datetime import time, datetime
# Create time
lunch_time = time(12, 30, 0)
print(f"Lunch: {lunch_time}")
# Current time from datetime
now = datetime.now()
print(f"Hour: {now.hour}")
print(f"Minute: {now.minute}")
print(f"Second: {now.second}")
# Create datetime
meeting = datetime(2024, 12, 25, 14, 30)
print(f"Meeting: {meeting}")
Formatting Dates
- strftime() formats datetime as string
- strptime() parses string to datetime
- Format codes: %Y (year), %m (month), %d (day)
- Time codes: %H (hour), %M (minute), %S (second)
from datetime import datetime
now = datetime.now()
# Format datetime as string
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted: {formatted}")
# Different formats
print(now.strftime("%B %d, %Y"))
print(now.strftime("%m/%d/%y"))
print(now.strftime("%A, %I:%M %p"))
# Parse string to datetime
date_str = "2024-12-25"
parsed = datetime.strptime(date_str, "%Y-%m-%d")
print(f"Parsed: {parsed}")
Date Arithmetic
- timedelta represents duration between dates
- Can add/subtract timedeltas from dates
- Calculate difference between two dates
- Useful for scheduling and deadlines
from datetime import datetime, timedelta
now = datetime.now()
# Add days
tomorrow = now + timedelta(days=1)
next_week = now + timedelta(weeks=1)
print(f"Tomorrow: {tomorrow.date()}")
print(f"Next week: {next_week.date()}")
# Subtract days
yesterday = now - timedelta(days=1)
print(f"Yesterday: {yesterday.date()}")
# Calculate difference
birthday = datetime(2024, 12, 25)
diff = birthday - now
print(f"Days until birthday: {diff.days}")
# Time operations
future = now + timedelta(hours=2, minutes=30)
print(f"In 2.5 hours: {future.strftime('%H:%M')}")