⏱️ Calculating Date Differences
Calculating differences between dates and times is essential for scheduling, analytics, and understanding time spans. Python's timedelta
class makes it easy to work with durations and perform date arithmetic.
from datetime import datetime, timedelta
# Calculate difference between two dates
start_date = datetime(2024, 1, 1)
end_date = datetime(2024, 3, 15)
difference = end_date - start_date
print(f"Difference: {difference}")
print(f"Days: {difference.days}")
print(f"Total seconds: {difference.total_seconds()}")
🎯 Understanding Timedelta
Timedelta represents a duration - the difference between two dates or times.
Basic Date Arithmetic
from datetime import datetime, timedelta
now = datetime.now()
print(f"Current time: {now}")
# Add time
future = now + timedelta(days=7, hours=3, minutes=30)
print(f"In 7 days, 3 hours, 30 minutes: {future}")
# Subtract time
past = now - timedelta(weeks=2, days=3)
print(f"2 weeks and 3 days ago: {past}")
# Calculate difference
diff = future - now
print(f"Time until future: {diff}")
Creating Timedelta Objects
from datetime import timedelta
# Different ways to create timedelta
one_week = timedelta(weeks=1)
one_day = timedelta(days=1)
one_hour = timedelta(hours=1)
thirty_minutes = timedelta(minutes=30)
combined = timedelta(days=5, hours=8, minutes=30, seconds=45)
print(f"One week: {one_week}")
print(f"One day: {one_day}")
print(f"One hour: {one_hour}")
print(f"Thirty minutes: {thirty_minutes}")
print(f"Combined: {combined}")
# Get total seconds for different durations
print(f"Week in seconds: {one_week.total_seconds()}")
print(f"Day in seconds: {one_day.total_seconds()}")
Date Difference Calculations
from datetime import datetime, date
# Calculate age in different units
birth_date = datetime(1990, 5, 15)
now = datetime.now()
age_delta = now - birth_date
print(f"Age in days: {age_delta.days}")
print(f"Age in years (approx): {age_delta.days // 365}")
# Calculate project duration
project_start = datetime(2024, 1, 15)
project_end = datetime(2024, 6, 30)
duration = project_end - project_start
print(f"Project duration: {duration.days} days")
print(f"Project duration: {duration.days / 7:.1f} weeks")
📊 Time Difference Utilities
Useful functions for working with time differences.
Duration Formatting
from datetime import timedelta
def format_duration(td):
"""Format timedelta in a human-readable way"""
total_seconds = int(td.total_seconds())
days = td.days
hours = total_seconds // 3600 % 24
minutes = total_seconds // 60 % 60
seconds = total_seconds % 60
parts = []
if days:
parts.append(f"{days} day{'s' if days != 1 else ''}")
if hours:
parts.append(f"{hours} hour{'s' if hours != 1 else ''}")
if minutes:
parts.append(f"{minutes} minute{'s' if minutes != 1 else ''}")
if seconds and not (days or hours):
parts.append(f"{seconds} second{'s' if seconds != 1 else ''}")
return ', '.join(parts) if parts else '0 seconds'
# Example usage
durations = [
timedelta(days=5, hours=3, minutes=30),
timedelta(hours=2, minutes=45),
timedelta(minutes=30),
timedelta(seconds=45)
]
for duration in durations:
print(f"{duration} → {format_duration(duration)}")
Business Days Calculation
from datetime import datetime, timedelta
def count_business_days(start_date, end_date):
"""Count business days between two dates (excluding weekends)"""
business_days = 0
current_date = start_date
while current_date < end_date:
# Monday = 0, Sunday = 6
if current_date.weekday() < 5: # Monday to Friday
business_days += 1
current_date += timedelta(days=1)
return business_days
def add_business_days(start_date, business_days):
"""Add business days to a date (excluding weekends)"""
current_date = start_date
days_added = 0
while days_added < business_days:
current_date += timedelta(days=1)
if current_date.weekday() < 5: # Monday to Friday
days_added += 1
return current_date
# Example usage
start = datetime(2024, 3, 15) # Assuming it's a weekday
end = datetime(2024, 3, 25)
biz_days = count_business_days(start, end)
print(f"Business days between {start.date()} and {end.date()}: {biz_days}")
future_biz_date = add_business_days(start, 10)
print(f"10 business days after {start.date()}: {future_biz_date.date()}")
Time Until/Since Events
from datetime import datetime, timedelta
def time_until_event(event_date):
"""Calculate time remaining until an event"""
now = datetime.now()
if event_date > now:
diff = event_date - now
return f"Time until event: {format_duration(diff)}"
else:
diff = now - event_date
return f"Event was {format_duration(diff)} ago"
def format_duration(td):
"""Simple duration formatter"""
days = td.days
hours = td.seconds // 3600
minutes = (td.seconds % 3600) // 60
if days > 0:
return f"{days} days, {hours} hours"
elif hours > 0:
return f"{hours} hours, {minutes} minutes"
else:
return f"{minutes} minutes"
# Example events
events = [
("New Year 2025", datetime(2025, 1, 1)),
("Yesterday", datetime.now() - timedelta(days=1)),
("Next Week", datetime.now() + timedelta(weeks=1))
]
for name, date in events:
print(f"{name}: {time_until_event(date)}")
📈 Advanced Time Calculations
More sophisticated time difference calculations.
Working Hours Calculator
from datetime import datetime, time, timedelta
def calculate_working_hours(start_datetime, end_datetime,
work_start=time(9, 0), work_end=time(17, 0)):
"""Calculate working hours between two datetimes"""
total_hours = 0
current_date = start_datetime.date()
end_date = end_datetime.date()
while current_date <= end_date:
# Skip weekends
if current_date.weekday() >= 5:
current_date += timedelta(days=1)
continue
# Determine work period for this day
day_start = datetime.combine(current_date, work_start)
day_end = datetime.combine(current_date, work_end)
# Adjust for actual start/end times
period_start = max(day_start, start_datetime)
period_end = min(day_end, end_datetime)
# Add hours if there's overlap
if period_start < period_end:
hours = (period_end - period_start).total_seconds() / 3600
total_hours += hours
current_date += timedelta(days=1)
return total_hours
# Example usage
project_start = datetime(2024, 3, 15, 14, 30) # Friday 2:30 PM
project_end = datetime(2024, 3, 18, 11, 0) # Monday 11:00 AM
working_hours = calculate_working_hours(project_start, project_end)
print(f"Total working hours: {working_hours:.2f}")
Age Calculations
from datetime import datetime, date
def calculate_precise_age(birth_date, reference_date=None):
"""Calculate precise age in years, months, and days"""
if reference_date is None:
reference_date = date.today()
years = reference_date.year - birth_date.year
months = reference_date.month - birth_date.month
days = reference_date.day - birth_date.day
# Adjust for negative days
if days < 0:
months -= 1
# Get days in previous month
if reference_date.month == 1:
prev_month = date(reference_date.year - 1, 12, 1)
else:
prev_month = date(reference_date.year, reference_date.month - 1, 1)
next_month = date(prev_month.year, prev_month.month + 1, 1)
days_in_prev_month = (next_month - prev_month).days
days += days_in_prev_month
# Adjust for negative months
if months < 0:
years -= 1
months += 12
return years, months, days
# Example usage
birth = date(1990, 8, 25)
years, months, days = calculate_precise_age(birth)
print(f"Age: {years} years, {months} months, {days} days")
# Calculate age at specific date
specific_date = date(2024, 12, 31)
y, m, d = calculate_precise_age(birth, specific_date)
print(f"Age on {specific_date}: {y} years, {m} months, {d} days")
📊 Timedelta Reference
Operation | Example | Result |
---|---|---|
Create | timedelta(days=7) | 7 days duration |
Add to date | date + timedelta(days=1) | Next day |
Subtract from date | date - timedelta(hours=2) | 2 hours earlier |
Date difference | date2 - date1 | Timedelta object |
Total seconds | td.total_seconds() | Duration in seconds |
Multiply | timedelta(hours=1) * 3 | 3 hours |
Compare | td1 > td2 | Boolean comparison |
🎯 Key Takeaways
🚀 What's Next?
Now that you can calculate time differences, learn how to parse date strings from text input.
Continue to: Parse Date Strings
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.