Practical Range Operations
Common Date Range Manipulations
from datetime import datetime, timedelta
def filter_date_range(date_range, condition):
return [date for date in date_range if condition(date)]
## Example: Filter business days
def is_business_day(date):
return date.weekday() < 5
start = datetime(2023, 1, 1)
end = datetime(2023, 1, 31)
date_range = [start + timedelta(days=x) for x in range((end - start).days + 1)]
business_days = filter_date_range(date_range, is_business_day)
Advanced Range Calculations
Date Range Aggregations
import pandas as pd
import numpy as np
## Create sample time series data
dates = pd.date_range(start='2023-01-01', end='2023-12-31', freq='D')
values = np.random.rand(len(dates))
time_series = pd.Series(values, index=dates)
## Aggregation techniques
monthly_avg = time_series.resample('M').mean()
quarterly_sum = time_series.resample('Q').sum()
Range Operation Techniques
Operation |
Method |
Description |
Filtering |
List Comprehension |
Select specific dates |
Aggregation |
Pandas Resample |
Group and summarize |
Transformation |
Map/Apply |
Modify date attributes |
Comparison |
Date Comparisons |
Check date relationships |
Complex Range Scenarios
from datetime import datetime, timedelta
class DateRangeProcessor:
@staticmethod
def overlap_detection(range1, range2):
return max(range1[0], range2[0]) <= min(range1[1], range2[1])
@staticmethod
def merge_overlapping_ranges(ranges):
sorted_ranges = sorted(ranges, key=lambda x: x[0])
merged = []
for current in sorted_ranges:
if not merged or current[0] > merged[-1][1]:
merged.append(current)
else:
merged[-1] = (merged[-1][0], max(merged[-1][1], current[1]))
return merged
## Example usage
ranges = [
(datetime(2023, 1, 1), datetime(2023, 1, 15)),
(datetime(2023, 1, 10), datetime(2023, 1, 25)),
(datetime(2023, 1, 30), datetime(2023, 2, 10))
]
merged_ranges = DateRangeProcessor.merge_overlapping_ranges(ranges)
Range Operation Workflow
flowchart TD
A[Date Range Input] --> B{Preprocessing}
B --> C[Filtering]
B --> D[Transformation]
C --> E[Aggregation]
D --> E
E --> F[Final Result]
def optimize_range_processing(large_date_range):
## Use generators for memory efficiency
def process_chunk(chunk):
return [item for item in chunk if some_condition(item)]
## Process in chunks
chunk_size = 1000
processed_results = []
for i in range(0, len(large_date_range), chunk_size):
chunk = large_date_range[i:i+chunk_size]
processed_results.extend(process_chunk(chunk))
return processed_results
LabEx Best Practices
When performing range operations in LabEx Python environments:
- Use vectorized operations
- Leverage pandas for complex manipulations
- Implement lazy evaluation techniques
- Consider memory efficiency for large datasets
Error Handling and Validation
def validate_date_range(start, end):
try:
assert start < end, "Start date must be before end date"
assert isinstance(start, datetime), "Invalid start date type"
assert isinstance(end, datetime), "Invalid end date type"
return True
except AssertionError as e:
print(f"Range validation error: {e}")
return False
By mastering these practical range operations, developers can efficiently manipulate and process date ranges in various Python applications.