Advanced Date Manipulation
Complex Date Calculations
Time Zone Handling
from datetime import datetime
from zoneinfo import ZoneInfo
## Working with multiple time zones
ny_time = datetime.now(ZoneInfo('America/New_York'))
tokyo_time = datetime.now(ZoneInfo('Asia/Tokyo'))
Date Range Generation
Creating Comprehensive Date Ranges
from datetime import date, timedelta
def generate_date_range(start_date, end_date):
delta = end_date - start_date
return [start_date + timedelta(days=i) for i in range(delta.days + 1)]
Advanced Filtering Techniques
Date-Based Filtering
def filter_dates_by_condition(dates, condition):
return [date for date in dates if condition(date)]
## Example: Filter weekends
weekend_dates = filter_dates_by_condition(
date_range,
lambda x: x.weekday() in [5, 6]
)
Date Manipulation Strategies
Strategy |
Description |
Use Case |
Range Generation |
Create sequence of dates |
Reporting, Scheduling |
Filtering |
Select dates based on conditions |
Data Analysis |
Transformation |
Modify date attributes |
Calendar Applications |
Complex Calculation Workflow
graph TD
A[Start Date] --> B[Define Calculation Parameters]
B --> C{Calculation Type}
C -->|Range| D[Generate Date Range]
C -->|Filter| E[Apply Date Conditions]
C -->|Transform| F[Modify Date Attributes]
D --> G[Process Results]
E --> G
F --> G
Business Day Calculations
from datetime import date, timedelta
import holidays
def next_business_day(current_date, country='US'):
us_holidays = holidays.US()
next_day = current_date + timedelta(days=1)
while next_day.weekday() >= 5 or next_day in us_holidays:
next_day += timedelta(days=1)
return next_day
from functools import lru_cache
@lru_cache(maxsize=1000)
def cached_date_calculation(base_date, days):
return base_date + timedelta(days=days)
Advanced Time Calculations
from dateutil.relativedelta import relativedelta
def complex_date_shift(base_date, **kwargs):
return base_date + relativedelta(**kwargs)
## Example usage
result = complex_date_shift(
date.today(),
months=+3,
days=+15,
weekday=3 ## Ensures Wednesday
)
LabEx Learning Tip
Advanced date manipulation requires practice. LabEx provides interactive Python environments to experiment with these complex techniques safely and effectively.
Best Practices
- Use built-in libraries for complex calculations
- Handle edge cases and boundary conditions
- Implement caching for repetitive calculations
- Consider performance implications
- Always validate date transformations
Error Handling Strategies
def safe_date_manipulation(operation, default=None):
try:
return operation()
except (ValueError, TypeError) as e:
print(f"Date manipulation error: {e}")
return default