Date Range Calculations
Generating Date Sequences
from datetime import date, timedelta
def generate_date_range(start_date, end_date):
current = start_date
while current <= end_date:
yield current
current += timedelta(days=1)
start = date(2023, 1, 1)
end = date(2023, 1, 10)
for single_date in generate_date_range(start, end):
print(single_date)
Date Manipulation Techniques
Age Calculation
from datetime import date
def calculate_age(birth_date):
today = date.today()
age = today.year - birth_date.year
## Adjust age if birthday hasn't occurred this year
if (today.month, today.day) < (birth_date.month, birth_date.day):
age -= 1
return age
birth = date(1990, 5, 15)
print(f"Current Age: {calculate_age(birth)}")
graph TD
A[Original Date] --> B[Transformation]
B --> C[Add/Subtract Days]
B --> D[Start/End of Month]
B --> E[Day of Week]
B --> F[Timezone Conversion]
Transformation |
Method |
Example |
First Day of Month |
replace(day=1) |
Get month's start |
Last Day of Month |
Custom calculation |
Find last day |
Next Business Day |
Custom logic |
Skip weekends |
Fiscal Year Start |
Date adjustment |
Align with fiscal calendar |
Month-End Calculation
from datetime import date
from calendar import monthrange
def get_last_day_of_month(year, month):
return date(year, month, monthrange(year, month)[1])
current_date = date.today()
last_day = get_last_day_of_month(current_date.year, current_date.month)
print(f"Last day of current month: {last_day}")
Working with Business Days
from datetime import date, timedelta
def next_business_day(input_date):
while input_date.weekday() >= 5: ## 5, 6 are Saturday, Sunday
input_date += timedelta(days=1)
return input_date
today = date.today()
next_work_day = next_business_day(today)
print(f"Next business day: {next_work_day}")
Date Comparison Strategies
def is_weekend(check_date):
return check_date.weekday() >= 5
def is_holiday(check_date):
## Placeholder for holiday logic
holidays = [
date(check_date.year, 1, 1), ## New Year's Day
date(check_date.year, 12, 25) ## Christmas
]
return check_date in holidays
current = date.today()
print(f"Is weekend: {is_weekend(current)}")
print(f"Is holiday: {is_holiday(current)}")
LabEx Pro Tip
When performing complex date transformations, LabEx recommends creating reusable utility functions to handle common date manipulation scenarios efficiently.
def safe_date_transform(input_date, days_offset=0):
try:
transformed_date = input_date + timedelta(days=days_offset)
return transformed_date
except Exception as e:
print(f"Transformation error: {e}")
return input_date