Date Calculator Script
Objective
Build a date calculation utility: compute differences, add/subtract time periods, and handle timezones.
Tools & Technologies
datetimetimedeltadateutilstrftimetimezone
Key Commands
from datetime import datetime, timedeltadatetime.strptime('2024-01-15','%Y-%m-%d')(d2-d1).daysdatetime.now(timezone.utc)Architecture Overview
flowchart LR
INPUT[Date string\n'2024-01-15'] --> PARSE[strptime\nparse to datetime]
PARSE --> ARITH[Arithmetic\n+ timedelta\n- timedelta]
ARITH --> COMPARE[Compare\nd1 < d2]
ARITH --> FORMAT[strftime\nformat to string]
FORMAT --> OUTPUT[Output\n'January 15, 2024']
style PARSE fill:#1a1a2e,stroke:#00d4ff,color:#e0e0e0
style OUTPUT fill:#1a1a2e,stroke:#00ff88,color:#e0e0e0
Step-by-Step Process
01
Date Arithmetic
Add and subtract time periods.
from datetime import datetime, timedelta
now = datetime.now()
print(f'Today: {now.strftime("%Y-%m-%d")}')
# Add 30 days
future = now + timedelta(days=30)
print(f'In 30 days: {future.strftime("%Y-%m-%d")}')
# Difference between dates
birthday = datetime(1999, 7, 15)
age_days = (now - birthday).days
print(f'Age in days: {age_days}')
print(f'Age in years: {age_days // 365}')
02
Parse and Format
Convert between strings and datetime objects.
# Parse various formats
d1 = datetime.strptime('2024-01-15', '%Y-%m-%d')
d2 = datetime.strptime('15/01/2024', '%d/%m/%Y')
d3 = datetime.strptime('January 15, 2024', '%B %d, %Y')
# Format
print(d1.strftime('%B %d, %Y')) # January 15, 2024
print(d1.strftime('%Y-%m-%dT%H:%M')) # 2024-01-15T00:00
print(d1.isoformat()) # ISO 8601
Challenges & Solutions
- Naive datetime (no timezone) comparisons with aware datetime (with tz) raise TypeError
- strptime format must match exactly — extra spaces cause ValueError
Key Takeaways
- Store all datetimes as UTC internally, convert to local time only for display
- zoneinfo (Python 3.9+) is the standard library alternative to pytz