Weekday Manipulation
Weekday Calculation Techniques
Weekday manipulation involves various operations to modify, calculate, and transform datetime objects based on weekday properties.
Finding Next and Previous Weekdays
from datetime import datetime, timedelta
def get_next_weekday(date, days=1):
next_date = date + timedelta(days=days)
return next_date
def get_previous_weekday(date, days=1):
previous_date = date - timedelta(days=days)
return previous_date
## Example usage
current_date = datetime.now()
next_week_date = get_next_weekday(current_date, 7)
previous_week_date = get_previous_weekday(current_date, 7)
Weekday Filtering and Selection
def filter_weekdays(start_date, end_date):
current_date = start_date
weekdays = []
while current_date <= end_date:
if current_date.weekday() < 5: ## Weekdays only
weekdays.append(current_date)
current_date += timedelta(days=1)
return weekdays
## Example usage
start = datetime(2023, 6, 1)
end = datetime(2023, 6, 30)
business_days = filter_weekdays(start, end)
graph TD
A[Original Date] --> B{Weekday Analysis}
B --> C[Next Weekday]
B --> D[Previous Weekday]
B --> E[Weekday Filtering]
Advanced Weekday Calculations
Operation |
Description |
Method |
Next Weekday |
Find next business day |
timedelta |
Previous Weekday |
Find previous business day |
timedelta |
Weekday Count |
Count specific weekdays |
Iteration |
Weekday Mapping |
Transform weekday representation |
Custom function |
Handling Special Cases
def adjust_to_business_day(date):
while date.weekday() >= 5: ## Weekend adjustment
date += timedelta(days=1)
return date
## Example usage
weekend_date = datetime(2023, 6, 17) ## Saturday
business_date = adjust_to_business_day(weekend_date)
def get_nth_weekday(year, month, weekday, nth):
from calendar import monthrange
first_day = datetime(year, month, 1)
days_in_month = monthrange(year, month)[1]
occurrences = [
date for date in (first_day + timedelta(days=d)
for d in range(days_in_month))
if date.weekday() == weekday
]
return occurrences[nth - 1] if nth <= len(occurrences) else None
## Example: Find 3rd Wednesday of June 2023
third_wednesday = get_nth_weekday(2023, 6, 2, 3)
- Use
timedelta
for efficient date calculations
- Minimize iterations for large date ranges
- Consider vectorized operations for bulk processing
LabEx recommends practicing these techniques to enhance datetime manipulation skills in Python.
Error Handling and Validation
def validate_weekday_operation(operation):
try:
result = operation()
return result
except ValueError as e:
print(f"Invalid weekday operation: {e}")
return None