Practical Date Scenarios
Real-World Date Handling Challenges
1. Age Calculation
from datetime import date
def calculate_age(birthdate):
today = date.today()
age = today.year - birthdate.year
## Adjust age if birthday hasn't occurred this year
if (today.month, today.day) < (birthdate.month, birthdate.day):
age -= 1
return age
## Example usage
birth_date = date(1990, 5, 15)
print(f"Age: {calculate_age(birth_date)} years")
2. Event Scheduling and Reminders
from datetime import datetime, timedelta
class EventScheduler:
def __init__(self):
self.events = []
def add_event(self, name, event_date):
self.events.append({
'name': name,
'date': event_date
})
def get_upcoming_events(self, days_ahead=7):
today = datetime.now()
upcoming = [
event for event in self.events
if today <= event['date'] <= today + timedelta(days=days_ahead)
]
return upcoming
## Example usage
scheduler = EventScheduler()
scheduler.add_event('Team Meeting', datetime(2023, 7, 1, 10, 0))
scheduler.add_event('Project Deadline', datetime(2023, 7, 5, 17, 0))
print("Upcoming Events:")
for event in scheduler.get_upcoming_events():
print(f"{event['name']} on {event['date']}")
3. Business Day Calculations
from datetime import date, timedelta
def is_business_day(check_date):
## Exclude weekends
if check_date.weekday() >= 5:
return False
## Optional: Add holiday exclusions
holidays = [
date(2023, 1, 1), ## New Year's Day
date(2023, 7, 4), ## Independence Day
]
return check_date not in holidays
def next_business_day(start_date):
next_day = start_date + timedelta(days=1)
while not is_business_day(next_day):
next_day += timedelta(days=1)
return next_day
## Example usage
today = date.today()
print(f"Next business day: {next_business_day(today)}")
Common Date Manipulation Scenarios
Scenario |
Technique |
Use Case |
Age Calculation |
Subtract birth year |
Verification systems |
Event Scheduling |
Date comparison |
Reminder applications |
Business Days |
Weekday checking |
Financial calculations |
Date Processing Workflow
flowchart TD
A[Input Date] --> B{Validate Date}
B -->|Valid| C[Process Date]
B -->|Invalid| D[Handle Error]
C --> E[Apply Business Logic]
E --> F[Output Result]
4. Date Range Analysis
def analyze_date_range(start_date, end_date):
total_days = (end_date - start_date).days
return {
'total_days': total_days,
'weeks': total_days // 7,
'weekend_days': sum(1 for i in range(total_days)
if (start_date + timedelta(days=i)).weekday() >= 5)
}
## Example usage
project_start = date(2023, 1, 1)
project_end = date(2023, 12, 31)
analysis = analyze_date_range(project_start, project_end)
print(f"Project Duration Analysis: {analysis}")
LabEx Tip
Practice these scenarios in LabEx's interactive Python environments to develop practical date manipulation skills.
Best Practices
- Always handle edge cases
- Consider time zones for global applications
- Use built-in Python date libraries
- Implement robust error handling