Practical Timedelta Use
Real-world Application Scenarios
1. Task Scheduling and Monitoring
from datetime import datetime, timedelta
class TaskScheduler:
def __init__(self, task_duration):
self.start_time = datetime.now()
self.task_duration = task_duration
def is_task_completed(self):
elapsed_time = datetime.now() - self.start_time
return elapsed_time <= self.task_duration
## Example usage
task = TaskScheduler(timedelta(hours=2))
def measure_execution_time(func):
start_time = datetime.now()
result = func()
execution_time = datetime.now() - start_time
print(f"Execution time: {execution_time}")
return result
Expiration and Timeout Handling
class TokenManager:
def __init__(self, token, validity_period):
self.token = token
self.issued_at = datetime.now()
self.validity_period = validity_period
def is_valid(self):
elapsed_time = datetime.now() - self.issued_at
return elapsed_time < self.validity_period
Time-based Data Filtering
def filter_recent_logs(logs, time_window):
current_time = datetime.now()
recent_logs = [
log for log in logs
if current_time - log.timestamp <= time_window
]
return recent_logs
Common Use Case Scenarios
Scenario |
Timedelta Application |
Example |
Session Management |
Token expiration |
timedelta(minutes=30) |
Caching |
Cache invalidation |
timedelta(hours=1) |
Billing |
Usage duration |
timedelta(days=30) |
Workflow Visualization
graph TD
A[Start] --> B{Check Time Condition}
B -->|Within Timeframe| C[Execute Action]
B -->|Expired| D[Handle Timeout]
Advanced Time Manipulation
Recurring Events
def generate_recurring_events(start_date, interval, count):
events = []
current_date = start_date
for _ in range(count):
events.append(current_date)
current_date += interval
return events
## Weekly recurring event
weekly_events = generate_recurring_events(
datetime.now(),
timedelta(days=7),
5
)
LabEx Pro Tip
Leverage timedelta for creating robust, time-sensitive applications that require precise time tracking and management.
Error Handling and Edge Cases
def safe_time_calculation(base_time, delta):
try:
result_time = base_time + delta
return result_time
except OverflowError:
print("Time calculation exceeded maximum range")
return None
This section demonstrates practical and advanced use cases of timedelta in Python, showcasing its versatility in solving real-world time-related programming challenges.