Date & Time
DateTime Calculations
Business applications need to calculate deadlines, subscription periods, and time between events. Python's timedelta class enables date arithmetic for adding days, finding durations, and computing working days. These calculations power scheduling, billing, and project management features.
DateTime calculations perform arithmetic with dates and times. Python uses timedelta for representing durations and performing date arithmetic.
Date Arithmetic
arithmetic.py
Replay: real traced execution (multi-file project)
# Add and subtract dates
from datetime import date, datetime, timedelta
# Date arithmetic
today = date(2025, 1, 29)
print("Today:", today)
print()
# Add days
print("Add days:")
print("Tomorrow:", today + timedelta(days=1))
print("+7 days:", today + timedelta(days=7))
print("+30 days:", today + timedelta(days=30))
# Add weeks
print("\nAdd weeks:")
print("+1 week:", today + timedelta(weeks=1))
print("+4 weeks:", today + timedelta(weeks=4))
# Subtract
print("\nSubtract:")
print("Yesterday:", today - timedelta(days=1))
print("-1 week:", today - timedelta(weeks=1))
print("-30 days:", today - timedelta(days=30))
# Chaining
print("\nChaining:")
future = today + timedelta(days=90) + timedelta(days=15)
print("+90 days +15 days:", future)
# Multiple units
print("\nMultiple units:")
delta = timedelta(days=7, hours=12, minutes=30)
print("Delta:", delta)
print("Total days:", delta.days)
print("Total seconds:", delta.total_seconds())
# DateTime arithmetic
print("\nDateTime arithmetic:")
now = datetime(2025, 1, 29, 14, 30, 0)
print("Now:", now)
print("+2 hours:", now + timedelta(hours=2))
print("+30 minutes:", now + timedelta(minutes=30))
print("+1 day 2 hours:", now + timedelta(days=1, hours=2))
# Negative timedeltas
print("\nNegative timedeltas:")
print("- 1 day:", today + timedelta(days=-1))
print("- 1 week:", today + timedelta(weeks=-1))
# End of periods
print("\nEnd of periods:")
print("End of week:", today + timedelta(weeks=1))
print("End of month:", today + timedelta(days=30))
print("End of quarter:", today + timedelta(days=90))
print("End of year:", today + timedelta(days=365))
# Practical examples
print("\nPractical examples:")
print("30-day trial ends:", today + timedelta(days=30))
print("90-day review:", today + timedelta(days=90))
print("1-year anniversary:", today + timedelta(days=365))
print("Two weeks notice:", today + timedelta(weeks=2))
# timedelta properties
print("\nTimedelta properties:")
td = timedelta(days=10, hours=5, minutes=30, seconds=45)
print("Timedelta:", td)
print("Days:", td.days)
print("Seconds:", td.seconds)
print("Total seconds:", td.total_seconds())
print("Total hours:", td.total_seconds() / 3600)
print("Total minutes:", td.total_seconds() / 60)
# Create from different units
print("\nCreate from units:")
print("7 days:", timedelta(days=7))
print("24 hours:", timedelta(hours=24))
print("1 week:", timedelta(weeks=1))
print("Combined:", timedelta(days=1, hours=12, minutes=30))
# Add and subtract dates
from datetime import date, datetime, timedelta
# Date arithmetic
today = date(2024, 2, 29)
print("Today:", today)
print()
# Add days
print("Add days:")
print("Tomorrow:", today + timedelta(days=1))
print("+7 days:", today + timedelta(days=7))
print("+30 days:", today + timedelta(days=30))
# Add weeks
print("\nAdd weeks:")
print("+1 week:", today + timedelta(weeks=1))
print("+4 weeks:", today + timedelta(weeks=4))
# Subtract
print("\nSubtract:")
print("Yesterday:", today - timedelta(days=1))
print("-1 week:", today - timedelta(weeks=1))
print("-30 days:", today - timedelta(days=30))
# Chaining
print("\nChaining:")
future = today + timedelta(days=90) + timedelta(days=15)
print("+90 days +15 days:", future)
# Multiple units
print("\nMultiple units:")
delta = timedelta(days=7, hours=12, minutes=30)
print("Delta:", delta)
print("Total days:", delta.days)
print("Total seconds:", delta.total_seconds())
# DateTime arithmetic
print("\nDateTime arithmetic:")
now = datetime(2025, 1, 29, 14, 30, 0)
print("Now:", now)
print("+2 hours:", now + timedelta(hours=2))
print("+30 minutes:", now + timedelta(minutes=30))
print("+1 day 2 hours:", now + timedelta(days=1, hours=2))
# Negative timedeltas
print("\nNegative timedeltas:")
print("- 1 day:", today + timedelta(days=-1))
print("- 1 week:", today + timedelta(weeks=-1))
# End of periods
print("\nEnd of periods:")
print("End of week:", today + timedelta(weeks=1))
print("End of month:", today + timedelta(days=30))
print("End of quarter:", today + timedelta(days=90))
print("End of year:", today + timedelta(days=365))
# Practical examples
print("\nPractical examples:")
print("30-day trial ends:", today + timedelta(days=30))
print("90-day review:", today + timedelta(days=90))
print("1-year anniversary:", today + timedelta(days=365))
print("Two weeks notice:", today + timedelta(weeks=2))
# timedelta properties
print("\nTimedelta properties:")
td = timedelta(days=10, hours=5, minutes=30, seconds=45)
print("Timedelta:", td)
print("Days:", td.days)
print("Seconds:", td.seconds)
print("Total seconds:", td.total_seconds())
print("Total hours:", td.total_seconds() / 3600)
print("Total minutes:", td.total_seconds() / 60)
# Create from different units
print("\nCreate from units:")
print("7 days:", timedelta(days=7))
print("24 hours:", timedelta(hours=24))
print("1 week:", timedelta(weeks=1))
print("Combined:", timedelta(days=1, hours=12, minutes=30))
# Add and subtract dates
from datetime import date, datetime, timedelta
# Date arithmetic
today = date(2026, 6, 15)
print("Today:", today)
print()
# Add days
print("Add days:")
print("Tomorrow:", today + timedelta(days=1))
print("+7 days:", today + timedelta(days=7))
print("+30 days:", today + timedelta(days=30))
# Add weeks
print("\nAdd weeks:")
print("+1 week:", today + timedelta(weeks=1))
print("+4 weeks:", today + timedelta(weeks=4))
# Subtract
print("\nSubtract:")
print("Yesterday:", today - timedelta(days=1))
print("-1 week:", today - timedelta(weeks=1))
print("-30 days:", today - timedelta(days=30))
# Chaining
print("\nChaining:")
future = today + timedelta(days=90) + timedelta(days=15)
print("+90 days +15 days:", future)
# Multiple units
print("\nMultiple units:")
delta = timedelta(days=7, hours=12, minutes=30)
print("Delta:", delta)
print("Total days:", delta.days)
print("Total seconds:", delta.total_seconds())
# DateTime arithmetic
print("\nDateTime arithmetic:")
now = datetime(2025, 1, 29, 14, 30, 0)
print("Now:", now)
print("+2 hours:", now + timedelta(hours=2))
print("+30 minutes:", now + timedelta(minutes=30))
print("+1 day 2 hours:", now + timedelta(days=1, hours=2))
# Negative timedeltas
print("\nNegative timedeltas:")
print("- 1 day:", today + timedelta(days=-1))
print("- 1 week:", today + timedelta(weeks=-1))
# End of periods
print("\nEnd of periods:")
print("End of week:", today + timedelta(weeks=1))
print("End of month:", today + timedelta(days=30))
print("End of quarter:", today + timedelta(days=90))
print("End of year:", today + timedelta(days=365))
# Practical examples
print("\nPractical examples:")
print("30-day trial ends:", today + timedelta(days=30))
print("90-day review:", today + timedelta(days=90))
print("1-year anniversary:", today + timedelta(days=365))
print("Two weeks notice:", today + timedelta(weeks=2))
# timedelta properties
print("\nTimedelta properties:")
td = timedelta(days=10, hours=5, minutes=30, seconds=45)
print("Timedelta:", td)
print("Days:", td.days)
print("Seconds:", td.seconds)
print("Total seconds:", td.total_seconds())
print("Total hours:", td.total_seconds() / 3600)
print("Total minutes:", td.total_seconds() / 60)
# Create from different units
print("\nCreate from units:")
print("7 days:", timedelta(days=7))
print("24 hours:", timedelta(hours=24))
print("1 week:", timedelta(weeks=1))
print("Combined:", timedelta(days=1, hours=12, minutes=30))
today ← 2025-01-29, future ← 2025-05-14, delta ← 7 days, 12:30:00
5# Date arithmetic6today→ 2025-01-29 = date(2025, 1, 29) #@today=date(2024, 2, 29), date(2026, 6, 15)7print("Today:", today2025-01-29)8print()910# Add days11print("Add days:")12print("Tomorrow:", today2025-01-29 + timedelta(days=1))13print("+7 days:", today2025-01-29 + timedelta(days=7))14print("+30 days:", today2025-01-29 + timedelta(days=30))1516# Add weeks17print("\nAdd weeks:")18print("+1 week:", today2025-01-29 + timedelta(weeks=1))19print("+4 weeks:", today2025-01-29 + timedelta(weeks=4))2021# Subtract22print("\nSubtract:")23print("Yesterday:", today2025-01-29 - timedelta(days=1))24print("-1 week:", today2025-01-29 - timedelta(weeks=1))25print("-30 days:", today2025-01-29 - timedelta(days=30))2627# Chaining28print("\nChaining:")29future→ 2025-05-14 = today2025-01-29 + timedelta(days=90) + timedelta(days=15)30print("+90 days +15 days:", future2025-05-14)3132# Multiple units33print("\nMultiple units:")34delta→ 7 days, 12:30:00 = timedelta(days=7, hours=12, minutes=30)35print("Delta:", delta7 days, 12:30:00)36print("Total days:", delta.days7)37print("Total seconds:", delta7 days, 12:30:00.total_seconds())3839# DateTime arithmetic40print("\nDateTime arithmetic:")41now→ 2025-01-29 14:30:00 = datetime(2025, 1, 29, 14, 30, 0)42print("Now:", now2025-01-29 14:30:00)43print("+2 hours:", now2025-01-29 14:30:00 + timedelta(hours=2))44print("+30 minutes:", now2025-01-29 14:30:00 + timedelta(minutes=30))45print("+1 day 2 hours:", now2025-01-29 14:30:00 + timedelta(days=1, hours=2))4647# Negative timedeltas48print("\nNegative timedeltas:")49print("- 1 day:", today2025-01-29 + timedelta(days=-1))50print("- 1 week:", today2025-01-29 + timedelta(weeks=-1))5152# End of periods53print("\nEnd of periods:")54print("End of week:", today2025-01-29 + timedelta(weeks=1))55print("End of month:", today2025-01-29 + timedelta(days=30))56print("End of quarter:", today2025-01-29 + timedelta(days=90))57print("End of year:", today2025-01-29 + timedelta(days=365))5859# Practical examples60print("\nPractical examples:")61print("30-day trial ends:", today2025-01-29 + timedelta(days=30))62print("90-day review:", today2025-01-29 + timedelta(days=90))63print("1-year anniversary:", today2025-01-29 + timedelta(days=365))64print("Two weeks notice:", today2025-01-29 + timedelta(weeks=2))6566# timedelta properties67print("\nTimedelta properties:")68td→ 10 days, 5:30:45 = timedelta(days=10, hours=5, minutes=30, seconds=45)69print("Timedelta:", td10 days, 5:30:45)70print("Days:", td.days10)71print("Seconds:", td.seconds19845)72print("Total seconds:", td10 days, 5:30:45.total_seconds())73print("Total hours:", td10 days, 5:30:45.total_seconds() / 3600)74print("Total minutes:", td10 days, 5:30:45.total_seconds() / 60)7576# Create from different units77print("\nCreate from units:")78print("7 days:", timedelta(days=7))79print("24 hours:", timedelta(hours=24))80print("1 week:", timedelta(weeks=1))81print("Combined:", timedelta(days=1, hours=12, minutes=30))outputToday: 2025-01-29 Add days: Tomorrow: 2025-01-30 +7 days: 2025-02-05 +30 days: 2025-02-28 Add weeks: +1 week: 2025-02-05 +4 weeks: 2025-02-26 Subtract: Yesterday: 2025-01-28 -1 week: 2025-01-22 -30 days: 2024-12-30 Chaining: +90 days +15 days: 2025-05-14 Multiple units: Delta: 7 days, 12:30:00 Total days: 7 Total seconds: 649800.0 DateTime arithmetic: Now: 2025-01-29 14:30:00 +2 hours: 2025-01-29 16:30:00 +30 minutes: 2025-01-29 15:00:00 +1 day 2 hours: 2025-01-30 16:30:00 Negative timedeltas: - 1 day: 2025-01-28 - 1 week: 2025-01-22 End of periods: End of week: 2025-02-05 End of month: 2025-02-28 End of quarter: 2025-04-29 End of year: 2026-01-29 Practical examples: 30-day trial ends: 2025-02-28 90-day review: 2025-04-29 1-year anniversary: 2026-01-29 Two weeks notice: 2025-02-12 Timedelta properties: Timedelta: 10 days, 5:30:45 Days: 10 Seconds: 19845 Total seconds: 883845.0 Total hours: 245.5125 Total minutes: 14730.75 Create from units: 7 days: 7 days, 0:00:00 24 hours: 1 day, 0:00:00 1 week: 7 days, 0:00:00 Combined: 1 day, 12:30:00
today ← 2024-02-29, future ← 2024-06-13, delta ← 7 days, 12:30:00
5# Date arithmetic6today→ 2024-02-29 = date(2024, 2, 29)7print("Today:", today2024-02-29)8print()910# Add days11print("Add days:")12print("Tomorrow:", today2024-02-29 + timedelta(days=1))13print("+7 days:", today2024-02-29 + timedelta(days=7))14print("+30 days:", today2024-02-29 + timedelta(days=30))1516# Add weeks17print("\nAdd weeks:")18print("+1 week:", today2024-02-29 + timedelta(weeks=1))19print("+4 weeks:", today2024-02-29 + timedelta(weeks=4))2021# Subtract22print("\nSubtract:")23print("Yesterday:", today2024-02-29 - timedelta(days=1))24print("-1 week:", today2024-02-29 - timedelta(weeks=1))25print("-30 days:", today2024-02-29 - timedelta(days=30))2627# Chaining28print("\nChaining:")29future→ 2024-06-13 = today2024-02-29 + timedelta(days=90) + timedelta(days=15)30print("+90 days +15 days:", future2024-06-13)3132# Multiple units33print("\nMultiple units:")34delta→ 7 days, 12:30:00 = timedelta(days=7, hours=12, minutes=30)35print("Delta:", delta7 days, 12:30:00)36print("Total days:", delta.days7)37print("Total seconds:", delta7 days, 12:30:00.total_seconds())3839# DateTime arithmetic40print("\nDateTime arithmetic:")41now→ 2025-01-29 14:30:00 = datetime(2025, 1, 29, 14, 30, 0)42print("Now:", now2025-01-29 14:30:00)43print("+2 hours:", now2025-01-29 14:30:00 + timedelta(hours=2))44print("+30 minutes:", now2025-01-29 14:30:00 + timedelta(minutes=30))45print("+1 day 2 hours:", now2025-01-29 14:30:00 + timedelta(days=1, hours=2))4647# Negative timedeltas48print("\nNegative timedeltas:")49print("- 1 day:", today2024-02-29 + timedelta(days=-1))50print("- 1 week:", today2024-02-29 + timedelta(weeks=-1))5152# End of periods53print("\nEnd of periods:")54print("End of week:", today2024-02-29 + timedelta(weeks=1))55print("End of month:", today2024-02-29 + timedelta(days=30))56print("End of quarter:", today2024-02-29 + timedelta(days=90))57print("End of year:", today2024-02-29 + timedelta(days=365))5859# Practical examples60print("\nPractical examples:")61print("30-day trial ends:", today2024-02-29 + timedelta(days=30))62print("90-day review:", today2024-02-29 + timedelta(days=90))63print("1-year anniversary:", today2024-02-29 + timedelta(days=365))64print("Two weeks notice:", today2024-02-29 + timedelta(weeks=2))6566# timedelta properties67print("\nTimedelta properties:")68td→ 10 days, 5:30:45 = timedelta(days=10, hours=5, minutes=30, seconds=45)69print("Timedelta:", td10 days, 5:30:45)70print("Days:", td.days10)71print("Seconds:", td.seconds19845)72print("Total seconds:", td10 days, 5:30:45.total_seconds())73print("Total hours:", td10 days, 5:30:45.total_seconds() / 3600)74print("Total minutes:", td10 days, 5:30:45.total_seconds() / 60)7576# Create from different units77print("\nCreate from units:")78print("7 days:", timedelta(days=7))79print("24 hours:", timedelta(hours=24))80print("1 week:", timedelta(weeks=1))81print("Combined:", timedelta(days=1, hours=12, minutes=30))outputToday: 2024-02-29 Add days: Tomorrow: 2024-03-01 +7 days: 2024-03-07 +30 days: 2024-03-30 Add weeks: +1 week: 2024-03-07 +4 weeks: 2024-03-28 Subtract: Yesterday: 2024-02-28 -1 week: 2024-02-22 -30 days: 2024-01-30 Chaining: +90 days +15 days: 2024-06-13 Multiple units: Delta: 7 days, 12:30:00 Total days: 7 Total seconds: 649800.0 DateTime arithmetic: Now: 2025-01-29 14:30:00 +2 hours: 2025-01-29 16:30:00 +30 minutes: 2025-01-29 15:00:00 +1 day 2 hours: 2025-01-30 16:30:00 Negative timedeltas: - 1 day: 2024-02-28 - 1 week: 2024-02-22 End of periods: End of week: 2024-03-07 End of month: 2024-03-30 End of quarter: 2024-05-29 End of year: 2025-02-28 Practical examples: 30-day trial ends: 2024-03-30 90-day review: 2024-05-29 1-year anniversary: 2025-02-28 Two weeks notice: 2024-03-14 Timedelta properties: Timedelta: 10 days, 5:30:45 Days: 10 Seconds: 19845 Total seconds: 883845.0 Total hours: 245.5125 Total minutes: 14730.75 Create from units: 7 days: 7 days, 0:00:00 24 hours: 1 day, 0:00:00 1 week: 7 days, 0:00:00 Combined: 1 day, 12:30:00
today ← 2026-06-15, future ← 2026-09-28, delta ← 7 days, 12:30:00
5# Date arithmetic6today→ 2026-06-15 = date(2026, 6, 15)7print("Today:", today2026-06-15)8print()910# Add days11print("Add days:")12print("Tomorrow:", today2026-06-15 + timedelta(days=1))13print("+7 days:", today2026-06-15 + timedelta(days=7))14print("+30 days:", today2026-06-15 + timedelta(days=30))1516# Add weeks17print("\nAdd weeks:")18print("+1 week:", today2026-06-15 + timedelta(weeks=1))19print("+4 weeks:", today2026-06-15 + timedelta(weeks=4))2021# Subtract22print("\nSubtract:")23print("Yesterday:", today2026-06-15 - timedelta(days=1))24print("-1 week:", today2026-06-15 - timedelta(weeks=1))25print("-30 days:", today2026-06-15 - timedelta(days=30))2627# Chaining28print("\nChaining:")29future→ 2026-09-28 = today2026-06-15 + timedelta(days=90) + timedelta(days=15)30print("+90 days +15 days:", future2026-09-28)3132# Multiple units33print("\nMultiple units:")34delta→ 7 days, 12:30:00 = timedelta(days=7, hours=12, minutes=30)35print("Delta:", delta7 days, 12:30:00)36print("Total days:", delta.days7)37print("Total seconds:", delta7 days, 12:30:00.total_seconds())3839# DateTime arithmetic40print("\nDateTime arithmetic:")41now→ 2025-01-29 14:30:00 = datetime(2025, 1, 29, 14, 30, 0)42print("Now:", now2025-01-29 14:30:00)43print("+2 hours:", now2025-01-29 14:30:00 + timedelta(hours=2))44print("+30 minutes:", now2025-01-29 14:30:00 + timedelta(minutes=30))45print("+1 day 2 hours:", now2025-01-29 14:30:00 + timedelta(days=1, hours=2))4647# Negative timedeltas48print("\nNegative timedeltas:")49print("- 1 day:", today2026-06-15 + timedelta(days=-1))50print("- 1 week:", today2026-06-15 + timedelta(weeks=-1))5152# End of periods53print("\nEnd of periods:")54print("End of week:", today2026-06-15 + timedelta(weeks=1))55print("End of month:", today2026-06-15 + timedelta(days=30))56print("End of quarter:", today2026-06-15 + timedelta(days=90))57print("End of year:", today2026-06-15 + timedelta(days=365))5859# Practical examples60print("\nPractical examples:")61print("30-day trial ends:", today2026-06-15 + timedelta(days=30))62print("90-day review:", today2026-06-15 + timedelta(days=90))63print("1-year anniversary:", today2026-06-15 + timedelta(days=365))64print("Two weeks notice:", today2026-06-15 + timedelta(weeks=2))6566# timedelta properties67print("\nTimedelta properties:")68td→ 10 days, 5:30:45 = timedelta(days=10, hours=5, minutes=30, seconds=45)69print("Timedelta:", td10 days, 5:30:45)70print("Days:", td.days10)71print("Seconds:", td.seconds19845)72print("Total seconds:", td10 days, 5:30:45.total_seconds())73print("Total hours:", td10 days, 5:30:45.total_seconds() / 3600)74print("Total minutes:", td10 days, 5:30:45.total_seconds() / 60)7576# Create from different units77print("\nCreate from units:")78print("7 days:", timedelta(days=7))79print("24 hours:", timedelta(hours=24))80print("1 week:", timedelta(weeks=1))81print("Combined:", timedelta(days=1, hours=12, minutes=30))outputToday: 2026-06-15 Add days: Tomorrow: 2026-06-16 +7 days: 2026-06-22 +30 days: 2026-07-15 Add weeks: +1 week: 2026-06-22 +4 weeks: 2026-07-13 Subtract: Yesterday: 2026-06-14 -1 week: 2026-06-08 -30 days: 2026-05-16 Chaining: +90 days +15 days: 2026-09-28 Multiple units: Delta: 7 days, 12:30:00 Total days: 7 Total seconds: 649800.0 DateTime arithmetic: Now: 2025-01-29 14:30:00 +2 hours: 2025-01-29 16:30:00 +30 minutes: 2025-01-29 15:00:00 +1 day 2 hours: 2025-01-30 16:30:00 Negative timedeltas: - 1 day: 2026-06-14 - 1 week: 2026-06-08 End of periods: End of week: 2026-06-22 End of month: 2026-07-15 End of quarter: 2026-09-13 End of year: 2027-06-15 Practical examples: 30-day trial ends: 2026-07-15 90-day review: 2026-09-13 1-year anniversary: 2027-06-15 Two weeks notice: 2026-06-29 Timedelta properties: Timedelta: 10 days, 5:30:45 Days: 10 Seconds: 19845 Total seconds: 883845.0 Total hours: 245.5125 Total minutes: 14730.75 Create from units: 7 days: 7 days, 0:00:00 24 hours: 1 day, 0:00:00 1 week: 7 days, 0:00:00 Combined: 1 day, 12:30:00
date_arithmetic
Adding and subtracting days, weeks, and other periods with timedelta
Calculating Differences
difference.py
Replay: real traced execution (multi-file project)
# Calculate differences
from datetime import date, datetime, timedelta
# Calculate difference
start = date(2025, 1, 1)
end = date(2025, 12, 31)
print("Start:", start)
print("End:", end)
print()
# Difference
diff = end - start
print("Difference:", diff)
print("Days:", diff.days)
print("Total seconds:", diff.total_seconds())
# Different date pairs
print("\nDifferent pairs:")
d1 = date(2020, 1, 15)
d2 = date(2025, 3, 20)
diff = d2 - d1
print(f"{d1} to {d2}")
print(f"Days: {diff.days}")
print(f"Weeks: {diff.days // 7}")
print(f"Approximate months: {diff.days // 30}")
print(f"Approximate years: {diff.days // 365}")
# DateTime differences
print("\nDateTime differences:")
dt1 = datetime(2025, 1, 29, 10, 0)
dt2 = datetime(2025, 1, 29, 15, 30)
diff = dt2 - dt1
print(f"{dt1} to {dt2}")
print(f"Difference: {diff}")
print(f"Hours: {diff.total_seconds() / 3600}")
print(f"Minutes: {diff.total_seconds() / 60}")
print(f"Seconds: {diff.total_seconds()}")
# Absolute difference
print("\nAbsolute difference:")
past = date(2020, 1, 1)
future = date(2030, 1, 1)
print("Past to future:", (future - past).days)
print("Future to past:", (past - future).days)
print("Absolute:", abs((past - future).days))
# Compare durations
print("\nCompare durations:")
delta1 = timedelta(days=7)
delta2 = timedelta(weeks=1)
delta3 = timedelta(days=10)
print(f"7 days == 1 week: {delta1 == delta2}")
print(f"7 days < 10 days: {delta1 < delta3}")
print(f"10 days > 1 week: {delta3 > delta2}")
# Practical examples
print("\nPractical examples:")
# Age calculation
birthday = date(1990, 3, 15)
today = date(2025, 1, 29)
age_days = (today - birthday).days
age_years = age_days // 365
print(f"Age: {age_years} years ({age_days} days)")
# Project duration
project_start = date(2025, 1, 1)
project_end = date(2025, 3, 31)
project_days = (project_end - project_start).days
print(f"Project duration: {project_days} days")
# Subscription length
sub_start = date(2024, 1, 1)
sub_end = date(2025, 1, 1)
sub_months = (sub_end - sub_start).days // 30
print(f"Subscription: approximately {sub_months} months")
# Time since event
event = date(2020, 3, 1)
days_since = (today - event).days
weeks_since = days_since // 7
print(f"Days since event: {days_since} ({weeks_since} weeks)")
# Time until event
future_event = date(2025, 7, 4)
days_until = (future_event - today).days
print(f"Days until event: {days_until}")
# Duration breakdown
print("\nDuration breakdown:")
total_delta = timedelta(days=100, hours=5, minutes=30)
print(f"Total: {total_delta}")
print(f"Days: {total_delta.days}")
print(f"Remaining seconds: {total_delta.seconds}")
print(f"Total hours: {total_delta.total_seconds() / 3600:.2f}")
# Helper function
def format_duration(td):
"""Format timedelta in readable form"""
days = td.days
hours = td.seconds // 3600
minutes = (td.seconds % 3600) // 60
seconds = td.seconds % 60
return f"{days}d {hours}h {minutes}m {seconds}s"
print("\nFormatted durations:")
print(format_duration(timedelta(days=5, hours=3, minutes=30, seconds=45)))
print(format_duration(timedelta(hours=25, minutes=90)))
start ← 2025-01-01, end ← 2025-12-31, diff ← 364 days, 0:00:00
5# Calculate difference6start→ 2025-01-01 = date(2025, 1, 1)7end→ 2025-12-31 = date(2025, 12, 31)89print("Start:", start2025-01-01)10print("End:", end2025-12-31)11print()1213# Difference14diff→ 364 days, 0:00:00 = end2025-12-31 - start2025-01-0115print("Difference:", diff364 days, 0:00:00)16print("Days:", diff.days364)17print("Total seconds:", diff364 days, 0:00:00.total_seconds())1819# Different date pairs20print("\nDifferent pairs:")21d1→ 2020-01-15 = date(2020, 1, 15)22d2→ 2025-03-20 = date(2025, 3, 20)2324diff→ 1891 days, 0:00:00 = d22025-03-20 - d12020-01-1525print(f"{d12020-01-15} to {d22025-03-20}")26print(f"Days: {diff.days1891}")27print(f"Weeks: {diff.days1891 // 7}")28print(f"Approximate months: {diff.days1891 // 30}")29print(f"Approximate years: {diff.days1891 // 365}")3031# DateTime differences32print("\nDateTime differences:")33dt1→ 2025-01-29 10:00:00 = datetime(2025, 1, 29, 10, 0)34dt2→ 2025-01-29 15:30:00 = datetime(2025, 1, 29, 15, 30)3536diff→ 5:30:00 = dt22025-01-29 15:30:00 - dt12025-01-29 10:00:0037print(f"{dt12025-01-29 10:00:00} to {dt22025-01-29 15:30:00}")38print(f"Difference: {diff5:30:00}")39print(f"Hours: {diff5:30:00.total_seconds() / 3600}")40print(f"Minutes: {diff5:30:00.total_seconds() / 60}")41print(f"Seconds: {diff5:30:00.total_seconds()}")4243# Absolute difference44print("\nAbsolute difference:")45past→ 2020-01-01 = date(2020, 1, 1)46future→ 2030-01-01 = date(2030, 1, 1)4748print("Past to future:", (future - past).days3653)49print("Future to past:", (past - future).days-3653)50print("Absolute:", abs((past - future).days-3653))5152# Compare durations53print("\nCompare durations:")54delta1→ 7 days, 0:00:00 = timedelta(days=7)55delta2→ 7 days, 0:00:00 = timedelta(weeks=1)56delta3→ 10 days, 0:00:00 = timedelta(days=10)5758print(f"7 days == 1 week: {delta17 days, 0:00:00 == delta27 days, 0:00:00}")59print(f"7 days < 10 days: {delta17 days, 0:00:00 < delta310 days, 0:00:00}")60print(f"10 days > 1 week: {delta310 days, 0:00:00 > delta27 days, 0:00:00}")6162# Practical examples63print("\nPractical examples:")6465# Age calculation66birthday→ 1990-03-15 = date(1990, 3, 15)67today→ 2025-01-29 = date(2025, 1, 29)68age_days→ 12739 = (today - birthday).days1273969age_years→ 34 = age_days12739 // 36570print(f"Age: {age_years34} years ({age_days12739} days)")7172# Project duration73project_start→ 2025-01-01 = date(2025, 1, 1)74project_end→ 2025-03-31 = date(2025, 3, 31)75project_days→ 89 = (project_end - project_start).days8976print(f"Project duration: {project_days89} days")7778# Subscription length79sub_start→ 2024-01-01 = date(2024, 1, 1)80sub_end→ 2025-01-01 = date(2025, 1, 1)81sub_months→ 12 = (sub_end - sub_start).days366 // 3082print(f"Subscription: approximately {sub_months12} months")8384# Time since event85event→ 2020-03-01 = date(2020, 3, 1)86days_since→ 1795 = (today - event).days179587weeks_since→ 256 = days_since1795 // 788print(f"Days since event: {days_since1795} ({weeks_since256} weeks)")8990# Time until event91future_event→ 2025-07-04 = date(2025, 7, 4)92days_until→ 156 = (future_event - today).days15693print(f"Days until event: {days_until156}")9495# Duration breakdown96print("\nDuration breakdown:")97total_delta→ 100 days, 5:30:00 = timedelta(days=100, hours=5, minutes=30)98print(f"Total: {total_delta100 days, 5:30:00}")99print(f"Days: {total_delta.days100}")100print(f"Remaining seconds: {total_delta.seconds19800}")101print(f"Total hours: {total_delta100 days, 5:30:00.total_seconds() / 3600:.2f}")102103# Helper function104def format_duration(td):105 """Format timedelta in readable form"""106 days = td.days107 hours = td.seconds // 3600108 minutes = (td.seconds % 3600) // 60109 seconds = td.seconds % 60110 return f"{days}d {hours}h {minutes}m {seconds}s"111112print("\nFormatted durations:")113print(format_duration(timedelta(days=5, hours=3, minutes=30, seconds=45)))114print(format_duration(timedelta(hours=25, minutes=90)))outputStart: 2025-01-01 End: 2025-12-31 Difference: 364 days, 0:00:00 Days: 364 Total seconds: 31449600.0 Different pairs: 2020-01-15 to 2025-03-20 Days: 1891 Weeks: 270 Approximate months: 63 Approximate years: 5 DateTime differences: 2025-01-29 10:00:00 to 2025-01-29 15:30:00 Difference: 5:30:00 Hours: 5.5 Minutes: 330.0 Seconds: 19800.0 Absolute difference: Past to future: 3653 Future to past: -3653 Absolute: 3653 Compare durations: 7 days == 1 week: True 7 days < 10 days: True 10 days > 1 week: True Practical examples: Age: 34 years (12739 days) Project duration: 89 days Subscription: approximately 12 months Days since event: 1795 (256 weeks) Days until event: 156 Duration breakdown: Total: 100 days, 5:30:00 Days: 100 Remaining seconds: 19800 Total hours: 2405.50 Formatted durations:days ← 5, hours ← 3, minutes ← 30, seconds ← 45
pass 1 of 2103# Helper function104def format_duration(td5 days, 3:30:45):105 """Format timedelta in readable form"""106 days→ 5 = td.days5107 hours→ 3 = td.seconds12645 // 3600108 minutes→ 30 = (td.seconds12645 % 3600) // 60109 seconds→ 45 = td.seconds12645 % 60110 return f"{days5}d {hours3}h {minutes30}m {seconds45}s"print(format_duration(timedelta(days=5, hours=3, minutes=30, seconds=4…
112print("\nFormatted durations:")113print(format_duration(timedelta(days=5, hours=3, minutes=30, seconds=45)))114print(format_duration(timedelta(hours=25, minutes=90)))output5d 3h 30m 45sdays ← 1, hours ← 2, minutes ← 30, seconds ← 0
pass 2 of 2103# Helper function104def format_duration(td1 day, 2:30:00):105 """Format timedelta in readable form"""106 days→ 1 = td.days1107 hours→ 2 = td.seconds9000 // 3600108 minutes→ 30 = (td.seconds9000 % 3600) // 60109 seconds→ 0 = td.seconds9000 % 60110 return f"{days1}d {hours2}h {minutes30}m {seconds0}s"print(format_duration(timedelta(hours=25, minutes=90)))
113print(format_duration(timedelta(days=5, hours=3, minutes=30, seconds=45)))114print(format_duration(timedelta(hours=25, minutes=90)))output1d 2h 30m 0s
date_difference
Finding the duration between two dates or datetimes
Day of Week
dayofweek.py
Replay: real traced execution (multi-file project)
# Day of week operations
from datetime import date, timedelta
import calendar
# Day of week
d = date(2025, 1, 29)
print("Date:", d)
print()
# Get day of week
weekday = d.weekday() # 0=Monday, 6=Sunday
isoweekday = d.isoweekday() # 1=Monday, 7=Sunday
print("weekday() (0=Mon, 6=Sun):", weekday)
print("isoweekday() (1=Mon, 7=Sun):", isoweekday)
print("Day name:", calendar.day_name[weekday])
print("Short day name:", calendar.day_abbr[weekday])
# Check specific days
print("\nCheck specific days:")
print("Is Monday?", weekday == 0)
print("Is Friday?", weekday == 4)
print("Is weekend?", weekday >= 5)
# All day names
print("\nAll day names:")
for i, day in enumerate(calendar.day_name):
print(f"{i}: {day}")
# Week navigation
print("\nThis week:")
# Find Monday
days_since_monday = weekday
monday = d - timedelta(days=days_since_monday)
for i in range(7):
day = monday + timedelta(days=i)
print(f"{calendar.day_name[day.weekday()]}: {day}")
# Next/previous specific day
print("\nNext/previous Monday:")
def next_weekday(d, target_weekday):
"""Get next occurrence of target weekday (0=Mon, 6=Sun)"""
days_ahead = target_weekday - d.weekday()
if days_ahead <= 0:
days_ahead += 7
return d + timedelta(days_ahead)
def previous_weekday(d, target_weekday):
"""Get previous occurrence of target weekday"""
days_behind = d.weekday() - target_weekday
if days_behind <= 0:
days_behind += 7
return d - timedelta(days_behind)
next_monday = next_weekday(d, 0)
prev_friday = previous_weekday(d, 4)
print("Next Monday:", next_monday)
print("Previous Friday:", prev_friday)
# Business days
print("\nBusiness days:")
def is_weekend(d):
"""Check if date is weekend"""
return d.weekday() >= 5
def next_business_day(d):
"""Get next business day"""
next_day = d + timedelta(days=1)
while is_weekend(next_day):
next_day += timedelta(days=1)
return next_day
def previous_business_day(d):
"""Get previous business day"""
prev_day = d - timedelta(days=1)
while is_weekend(prev_day):
prev_day -= timedelta(days=1)
return prev_day
print("Next business day:", next_business_day(d))
print("Previous business day:", previous_business_day(d))
# Count business days
def count_business_days(start, end):
"""Count business days between dates"""
count = 0
current = start
while current <= end:
if not is_weekend(current):
count += 1
current += timedelta(days=1)
return count
start = date(2025, 1, 27) # Monday
end = date(2025, 2, 7) # Friday
print(f"\nBusiness days from {start} to {end}:", count_business_days(start, end))
# Weekend check
print("\nWeekend check:")
test_dates = [
date(2025, 1, 27), # Monday
date(2025, 2, 1), # Saturday
date(2025, 2, 2) # Sunday
]
for td in test_dates:
status = "Weekend" if is_weekend(td) else "Weekday"
print(f"{td} ({calendar.day_name[td.weekday()]}): {status}")
# Add business days
def add_business_days(d, days):
"""Add business days to date"""
result = d
added = 0
while added < days:
result += timedelta(days=1)
if not is_weekend(result):
added += 1
return result
print("\nAdd business days:")
today = date(2025, 1, 29) # Wednesday
print(f"Today: {today} ({calendar.day_name[today.weekday()]})")
print("+5 business days:", add_business_days(today, 5))
# Week number
print("\nWeek information:")
iso = d.isocalendar()
print(f"ISO calendar: {iso}")
print(f"Year: {iso.year}")
print(f"Week: {iso.week}")
print(f"Weekday: {iso.weekday}")
# First/last day of week
print("\nFirst/last of week:")
first_day = d - timedelta(days=d.weekday())
last_day = first_day + timedelta(days=6)
print(f"First day (Monday): {first_day}")
print(f"Last day (Sunday): {last_day}")
d ← 2025-01-29, weekday ← 2, isoweekday ← 3
6# Day of week7d→ 2025-01-29 = date(2025, 1, 29)8print("Date:", d2025-01-29)9print()1011# Get day of week12weekday→ 2 = d2025-01-29.weekday() # 0=Monday, 6=Sunday13isoweekday→ 3 = d2025-01-29.isoweekday() # 1=Monday, 7=Sunday1415print("weekday() (0=Mon, 6=Sun):", weekday2)16print("isoweekday() (1=Mon, 7=Sun):", isoweekday3)17print("Day name:", calendar.day_name[weekday]Wednesday)18print("Short day name:", calendar.day_abbr[weekday]Wed)1920# Check specific days21print("\nCheck specific days:")22print("Is Monday?", weekday2 == 0)23print("Is Friday?", weekday2 == 4)24print("Is weekend?", weekday2 >= 5)2526# All day names27print("\nAll day names:")28for i, day in enumerate(calendar.day_name):outputDate: 2025-01-29 weekday() (0=Mon, 6=Sun): 2 isoweekday() (1=Mon, 7=Sun): 3 Day name: Wednesday Short day name: Wed Check specific days: Is Monday? Is Friday? Is weekend? All day names:for i, day in enumerate(calendar.day_name):
pass 1 of 727print("\nAll day names:")28for i0, dayMonday in enumerate(calendar.day_name⟨_localized_day A⟩):29 print(f"{i0}: {dayMonday}")output0: MondayAll 7 passes — pass 1 is the card above pass iday1 0 Monday 2 1 Tuesday 3 2 Wednesday 4 3 Thursday 5 4 Friday 6 5 Saturday 7 6 Sunday days_since_monday ← 2, monday ← 2025-01-27
31# Week navigation32print("\nThis week:")33# Find Monday34days_since_monday→ 2 = weekday235monday→ 2025-01-27 = d2025-01-29 - timedelta(days=days_since_monday2)36for i in range(7):output This week:day ← 2025-01-27
pass 1 of 735monday = d - timedelta(days=days_since_monday)36for i0 in range(7):37 day→ 2025-01-27 = monday2025-01-27 + timedelta(days=i0)38 print(f"{calendar.day_name⟨_localized_day A⟩[day2025-01-27.weekday()]}: {day}")outputMonday: 2025-01-27All 7 passes — pass 1 is the card above pass iday1 0 2025-01-27 2 1 2025-01-28 3 2 2025-01-29 4 3 2025-01-30 5 4 2025-01-31 6 5 2025-02-01 7 6 2025-02-02 next_monday = next_weekday(d, 0)
40# Next/previous specific day41print("\nNext/previous Monday:")42def next_weekday(d, target_weekday):43 """Get next occurrence of target weekday (0=Mon, 6=Sun)"""44 days_ahead = target_weekday - d.weekday()45 if days_ahead <= 0:46 days_ahead += 747 return d + timedelta(days_ahead)4849def previous_weekday(d, target_weekday):50 """Get previous occurrence of target weekday"""51 days_behind = d.weekday() - target_weekday52 if days_behind <= 0:53 days_behind += 754 return d - timedelta(days_behind)5556next_monday = next_weekday(d2025-01-29, 0)57prev_friday = previous_weekday(d, 4)output Next/previous Monday:days_ahead ← -2
41print("\nNext/previous Monday:")42def next_weekday(d2025-01-29, target_weekday0):43 """Get next occurrence of target weekday (0=Mon, 6=Sun)"""44 days_ahead→ -2 = target_weekday0 - d2025-01-29.weekday()45 if days_ahead <= 0:days_ahead ← 5
44days_ahead = target_weekday - d.weekday()45if days_ahead-2 <= 0:46 days_ahead→ 5 += 747return d + timedelta(days_ahead)return d + timedelta(days_ahead)
46 days_ahead += 747return d2025-01-29 + timedelta(days_ahead5)next_monday ← 2025-02-03
56next_monday→ 2025-02-03 = next_weekday(d2025-01-29, 0)57prev_friday = previous_weekday(d2025-01-29, 4)58print("Next Monday:", next_monday)days_behind ← -2
49def previous_weekday(d2025-01-29, target_weekday4):50 """Get previous occurrence of target weekday"""51 days_behind→ -2 = d2025-01-29.weekday() - target_weekday452 if days_behind <= 0:days_behind ← 5
51days_behind = d.weekday() - target_weekday52if days_behind-2 <= 0:53 days_behind→ 5 += 754return d - timedelta(days_behind)return d - timedelta(days_behind)
53 days_behind += 754return d2025-01-29 - timedelta(days_behind5)prev_friday ← 2025-01-24
56next_monday = next_weekday(d, 0)57prev_friday→ 2025-01-24 = previous_weekday(d2025-01-29, 4)58print("Next Monday:", next_monday2025-02-03)59print("Previous Friday:", prev_friday2025-01-24)6061# Business days62print("\nBusiness days:")63def is_weekend(d):64 """Check if date is weekend"""65 return d.weekday() >= 56667def next_business_day(d):68 """Get next business day"""69 next_day = d + timedelta(days=1)70 while is_weekend(next_day):71 next_day += timedelta(days=1)72 return next_day7374def previous_business_day(d):75 """Get previous business day"""76 prev_day = d - timedelta(days=1)77 while is_weekend(prev_day):78 prev_day -= timedelta(days=1)79 return prev_day8081print("Next business day:", next_business_day(d2025-01-29))82print("Previous business day:", previous_business_day(d))outputNext Monday: 2025-02-03 Previous Friday: 2025-01-24 Business days:next_day ← 2025-01-30
67def next_business_day(d2025-01-29):68 """Get next business day"""69 next_day→ 2025-01-30 = d2025-01-29 + timedelta(days=1)70 while is_weekend(next_day):def is_weekend(d):
pass 1 of 2462print("\nBusiness days:")63def is_weekend(d2025-01-30):64 """Check if date is weekend"""65 return d2025-01-30.weekday() >= 524 passes — pass 1 is the card above pass d1 2025-01-30 2 2025-01-28 3 2025-01-27 4 2025-01-28 5 2025-01-29 6 2025-01-30 7 2025-01-31 8 2025-02-01 9 2025-02-02 ⋯ 13 more passes ⋯ 23 2025-02-04 24 2025-02-05 return next_day
71 next_day += timedelta(days=1)72return next_day2025-01-30print("Next business day:", next_business_day(d))
81print("Next business day:", next_business_day(d2025-01-29))82print("Previous business day:", previous_business_day(d2025-01-29))outputNext business day: 2025-01-30prev_day ← 2025-01-28
74def previous_business_day(d2025-01-29):75 """Get previous business day"""76 prev_day→ 2025-01-28 = d2025-01-29 - timedelta(days=1)77 while is_weekend(prev_day):return prev_day
78 prev_day -= timedelta(days=1)79return prev_day2025-01-28start ← 2025-01-27, end ← 2025-02-07
81print("Next business day:", next_business_day(d))82print("Previous business day:", previous_business_day(d2025-01-29))8384# Count business days85def count_business_days(start, end):86 """Count business days between dates"""87 count = 088 current = start89 while current <= end:90 if not is_weekend(current):91 count += 192 current += timedelta(days=1)93 return count9495start→ 2025-01-27 = date(2025, 1, 27) # Monday96end→ 2025-02-07 = date(2025, 2, 7) # Friday97print(f"\nBusiness days from {start2025-01-27} to {end2025-02-07}:", count_business_days(start, end))outputPrevious business day: 2025-01-28count ← 0, current ← 2025-01-27
84# Count business days85def count_business_days(start2025-01-27, end2025-02-07):86 """Count business days between dates"""87 count→ 0 = 088 current→ 2025-01-27 = start2025-01-2789 while current <= end:while current <= end:
pass 1 of 1288current = start89while current2025-01-27 <= end2025-02-07:90 if not is_weekend(current):91 count += 1All 12 passes — pass 1 is the card above pass current1 2025-01-27 2 2025-01-28 3 2025-01-29 4 2025-01-30 5 2025-01-31 6 2025-02-01 7 2025-02-02 8 2025-02-03 9 2025-02-04 10 2025-02-05 11 2025-02-06 12 2025-02-07 count ← 1
pass 1 of 1089while current <= end:90 if not is_weekend(current2025-01-27):91 count→ 1 += 192 current += timedelta(days=1)All 10 passes — pass 1 is the card above pass currentcount1 2025-01-27 0 → 1 2 2025-01-28 1 → 2 3 2025-01-29 2 → 3 4 2025-01-30 3 → 4 5 2025-01-31 4 → 5 6 2025-02-03 5 → 6 7 2025-02-04 6 → 7 8 2025-02-05 7 → 8 9 2025-02-06 8 → 9 10 2025-02-07 9 → 10 current ← 2025-01-28
91 count += 192 current→ 2025-01-28 += timedelta(days=1)93return countcurrent ← 2025-01-29
91 count += 192 current→ 2025-01-29 += timedelta(days=1)93return countcurrent ← 2025-01-30
91 count += 192 current→ 2025-01-30 += timedelta(days=1)93return countcurrent ← 2025-01-31
91 count += 192 current→ 2025-01-31 += timedelta(days=1)93return countcurrent ← 2025-02-01
91 count += 192 current→ 2025-02-01 += timedelta(days=1)93return countcurrent ← 2025-02-02
91 count += 192 current→ 2025-02-02 += timedelta(days=1)93return countcurrent ← 2025-02-03
91 count += 192 current→ 2025-02-03 += timedelta(days=1)93return countcurrent ← 2025-02-04
91 count += 192 current→ 2025-02-04 += timedelta(days=1)93return countcurrent ← 2025-02-05
91 count += 192 current→ 2025-02-05 += timedelta(days=1)93return countcurrent ← 2025-02-06
91 count += 192 current→ 2025-02-06 += timedelta(days=1)93return countcurrent ← 2025-02-07
91 count += 192 current→ 2025-02-07 += timedelta(days=1)93return countcurrent ← 2025-02-08
91 count += 192 current→ 2025-02-08 += timedelta(days=1)93return countreturn count
92 current += timedelta(days=1)93return count10test_dates ← [datetime.date(2025, 1, 27), datetime.date(2025, 2, 1), datetime.date(2025, 2, 2)]
96end = date(2025, 2, 7) # Friday97print(f"\nBusiness days from {start2025-01-27} to {end2025-02-07}:", count_business_days(start, end))9899# Weekend check100print("\nWeekend check:")101test_dates→ [datetime.date(2025, 1, 27), datetime.date(2025, 2, 1), datetime.date(2025, 2, 2)] = [102 date(2025, 1, 27), # Monday103 date(2025, 2, 1), # Saturday104 date(2025, 2, 2) # Sunday105]output Business days from 2025-01-27 to 2025-02-07: 10 Weekend check:for td in test_dates:
pass 1 of 3107for td2025-01-27 in test_dates[datetime.date(2025, 1, 27), datetime.date(2025, 2, 1), datetime.date(2025, 2, 2)]:108 status = "Weekend" if is_weekend(td2025-01-27) else "Weekday"109 print(f"{td} ({calendar.day_name[td.weekday()]}): {status}")All 3 passes — pass 1 is the card above pass td1 2025-01-27 2 2025-02-01 3 2025-02-02 status ← Weekday
107for td in test_dates:108 status→ Weekday = "Weekend" if is_weekend(td2025-01-27) else "Weekday"109 print(f"{td2025-01-27} ({calendar.day_name⟨_localized_day A⟩[td.weekday()]}): {statusWeekday}")output2025-01-27 (Monday): Weekdaystatus ← Weekend
107for td in test_dates:108 status→ Weekend = "Weekend" if is_weekend(td2025-02-01) else "Weekday"109 print(f"{td2025-02-01} ({calendar.day_name⟨_localized_day A⟩[td.weekday()]}): {statusWeekend}")output2025-02-01 (Saturday): Weekendstatus ← Weekend
107for td in test_dates:108 status→ Weekend = "Weekend" if is_weekend(td2025-02-02) else "Weekday"109 print(f"{td2025-02-02} ({calendar.day_name⟨_localized_day A⟩[td.weekday()]}): {statusWeekend}")output2025-02-02 (Sunday): Weekendtoday ← 2025-01-29
122print("\nAdd business days:")123today→ 2025-01-29 = date(2025, 1, 29) # Wednesday124print(f"Today: {today2025-01-29} ({calendar.day_name⟨_localized_day A⟩[today.weekday()]})")125print("+5 business days:", add_business_days(today2025-01-29, 5))output Add business days: Today: 2025-01-29 (Wednesday)result ← 2025-01-29, added ← 0
111# Add business days112def add_business_days(d2025-01-29, days5):113 """Add business days to date"""114 result→ 2025-01-29 = d2025-01-29115 added→ 0 = 0116 while added < days:result ← 2025-01-30
pass 1 of 7115added = 0116while added0 < days5:117 result→ 2025-01-30 += timedelta(days=1)118 if not is_weekend(result):All 7 passes — pass 1 is the card above pass addedresult1 0 2025-01-29 → 2025-01-30 2 1 2025-01-30 → 2025-01-31 3 2 2025-01-31 → 2025-02-01 4 2 2025-02-01 → 2025-02-02 5 2 2025-02-02 → 2025-02-03 6 3 2025-02-03 → 2025-02-04 7 4 2025-02-04 → 2025-02-05 added ← 1
pass 1 of 5117 result += timedelta(days=1)118 if not is_weekend(result2025-01-30):119 added→ 1 += 1120return resultAll 5 passes — pass 1 is the card above pass resultadded1 2025-01-30 0 → 1 2 2025-01-31 1 → 2 3 2025-02-03 2 → 3 4 2025-02-04 3 → 4 5 2025-02-05 4 → 5 return result
119 added += 1120return result2025-02-05iso ← datetime.IsoCalendarDate(year=2025, week=5, weekday=3), first_day ← 2025-01-27
124print(f"Today: {today} ({calendar.day_name[today.weekday()]})")125print("+5 business days:", add_business_days(today2025-01-29, 5))126127# Week number128print("\nWeek information:")129iso→ datetime.IsoCalendarDate(year=2025, week=5, weekday=3) = d2025-01-29.isocalendar()130print(f"ISO calendar: {isodatetime.IsoCalendarDate(year=2025, week=5, weekday=3)}")131print(f"Year: {iso.year2025}")132print(f"Week: {iso.week5}")133print(f"Weekday: {iso.weekday3}")134135# First/last day of week136print("\nFirst/last of week:")137first_day→ 2025-01-27 = d2025-01-29 - timedelta(days=d.weekday())138last_day→ 2025-02-02 = first_day2025-01-27 + timedelta(days=6)139print(f"First day (Monday): {first_day2025-01-27}")140print(f"Last day (Sunday): {last_day2025-02-02}")output+5 business days: 2025-02-05 Week information: ISO calendar: datetime.IsoCalendarDate(year=2025, week=5, weekday=3) Year: 2025 Week: 5 Weekday: 3 First/last of week: First day (Monday): 2025-01-27 Last day (Sunday): 2025-02-02
day_of_week
Finding weekday, checking for weekends, and calendar operations
Age Calculation
age.py
Replay: real traced execution (multi-file project)
# Age calculation
from datetime import date, timedelta
# Age calculation
birthday = date(1990, 3, 15)
today = date(2025, 1, 29)
print("Birthdate:", birthday)
print("Today:", today)
print()
# Age in years (simple)
age_days = (today - birthday).days
age_years = age_days // 365
print("Age (simple):", age_years, "years")
# Age in years (accurate)
def calculate_age(birthdate, current_date):
"""Calculate age in years accounting for birthday"""
age = current_date.year - birthdate.year
# Check if birthday hasn't occurred yet this year
if current_date.month < birthdate.month or \
(current_date.month == birthdate.month and current_date.day < birthdate.day):
age -= 1
return age
age = calculate_age(birthday, today)
print("Age (accurate):", age, "years")
# Age breakdown
def age_breakdown(birthdate, current_date):
"""Calculate age in years, months, and days"""
years = calculate_age(birthdate, current_date)
# Calculate remaining months and days
if current_date.month >= birthdate.month:
months = current_date.month - birthdate.month
else:
months = 12 + current_date.month - birthdate.month
years -= 1
if current_date.day >= birthdate.day:
days = current_date.day - birthdate.day
else:
months -= 1
if months < 0:
months = 11
years -= 1
# Days in previous month
import calendar
prev_month = current_date.month - 1 if current_date.month > 1 else 12
prev_year = current_date.year if current_date.month > 1 else current_date.year - 1
days_in_prev = calendar.monthrange(prev_year, prev_month)[1]
days = days_in_prev - birthdate.day + current_date.day
return years, months, days
years, months, days = age_breakdown(birthday, today)
print(f"Age breakdown: {years} years, {months} months, {days} days")
# Age in different units
print("\nAge in different units:")
total_days = (today - birthday).days
print("Days:", total_days)
print("Weeks:", total_days // 7)
print("Months (approx):", total_days // 30)
print("Years (approx):", total_days // 365)
# Next birthday
def next_birthday(birthdate, current_date):
"""Calculate next birthday"""
next_bd = date(current_date.year, birthdate.month, birthdate.day)
if next_bd <= current_date:
next_bd = date(current_date.year + 1, birthdate.month, birthdate.day)
return next_bd
next_bd = next_birthday(birthday, today)
days_until = (next_bd - today).days
print("\nNext birthday:", next_bd)
print("Days until birthday:", days_until)
# Age at specific dates
print("\nAge at specific dates:")
check_dates = [
date(2020, 1, 1),
date(2025, 1, 1),
date(2030, 12, 31)
]
for check_date in check_dates:
age_at = calculate_age(birthday, check_date)
print(f"Age on {check_date}: {age_at}")
# Multiple people
print("\nMultiple people:")
people = [
(date(1990, 3, 15), "Person 1"),
(date(1985, 7, 22), "Person 2"),
(date(2000, 11, 30), "Person 3")
]
for birth, name in people:
years, months, days = age_breakdown(birth, today)
print(f"{name} (born {birth}): {years}y {months}m {days}d")
# Age verification
def is_minimum_age(birthdate, current_date, min_age):
"""Check if person meets minimum age"""
return calculate_age(birthdate, current_date) >= min_age
print("\nAge verification:")
print("Is 18 or older?", is_minimum_age(birthday, today, 18))
print("Is 21 or older?", is_minimum_age(birthday, today, 21))
print("Is 65 or older?", is_minimum_age(birthday, today, 65))
# Age groups
def get_age_group(birthdate, current_date):
"""Get age group category"""
age = calculate_age(birthdate, current_date)
if age < 13:
return "Child"
elif age < 18:
return "Teenager"
elif age < 65:
return "Adult"
else:
return "Senior"
print("\nAge group:", get_age_group(birthday, today))
# Milestone birthdays
print("\nMilestone birthdays:")
milestones = [18, 21, 30, 40, 50, 65]
current_age = calculate_age(birthday, today)
for milestone in milestones:
if milestone > current_age:
milestone_date = date(birthday.year + milestone, birthday.month, birthday.day)
days_until_milestone = (milestone_date - today).days
print(f"{milestone} years: {milestone_date} (in {days_until_milestone} days)")
# Retirement
print("\nRetirement:")
retirement_age = 65
retirement_date = date(birthday.year + retirement_age, birthday.month, birthday.day)
years_to_retirement = calculate_age(today, retirement_date)
days_to_retirement = (retirement_date - today).days
print("Retirement date:", retirement_date)
if retirement_date > today:
print("Years to retirement:", years_to_retirement)
print("Days to retirement:", days_to_retirement)
else:
print("Already retired")
# Age calculation
from datetime import date, timedelta
# Age calculation
birthday = date(1985, 7, 22)
today = date(2025, 1, 29)
print("Birthdate:", birthday)
print("Today:", today)
print()
# Age in years (simple)
age_days = (today - birthday).days
age_years = age_days // 365
print("Age (simple):", age_years, "years")
# Age in years (accurate)
def calculate_age(birthdate, current_date):
"""Calculate age in years accounting for birthday"""
age = current_date.year - birthdate.year
# Check if birthday hasn't occurred yet this year
if current_date.month < birthdate.month or \
(current_date.month == birthdate.month and current_date.day < birthdate.day):
age -= 1
return age
age = calculate_age(birthday, today)
print("Age (accurate):", age, "years")
# Age breakdown
def age_breakdown(birthdate, current_date):
"""Calculate age in years, months, and days"""
years = calculate_age(birthdate, current_date)
# Calculate remaining months and days
if current_date.month >= birthdate.month:
months = current_date.month - birthdate.month
else:
months = 12 + current_date.month - birthdate.month
years -= 1
if current_date.day >= birthdate.day:
days = current_date.day - birthdate.day
else:
months -= 1
if months < 0:
months = 11
years -= 1
# Days in previous month
import calendar
prev_month = current_date.month - 1 if current_date.month > 1 else 12
prev_year = current_date.year if current_date.month > 1 else current_date.year - 1
days_in_prev = calendar.monthrange(prev_year, prev_month)[1]
days = days_in_prev - birthdate.day + current_date.day
return years, months, days
years, months, days = age_breakdown(birthday, today)
print(f"Age breakdown: {years} years, {months} months, {days} days")
# Age in different units
print("\nAge in different units:")
total_days = (today - birthday).days
print("Days:", total_days)
print("Weeks:", total_days // 7)
print("Months (approx):", total_days // 30)
print("Years (approx):", total_days // 365)
# Next birthday
def next_birthday(birthdate, current_date):
"""Calculate next birthday"""
next_bd = date(current_date.year, birthdate.month, birthdate.day)
if next_bd <= current_date:
next_bd = date(current_date.year + 1, birthdate.month, birthdate.day)
return next_bd
next_bd = next_birthday(birthday, today)
days_until = (next_bd - today).days
print("\nNext birthday:", next_bd)
print("Days until birthday:", days_until)
# Age at specific dates
print("\nAge at specific dates:")
check_dates = [
date(2020, 1, 1),
date(2025, 1, 1),
date(2030, 12, 31)
]
for check_date in check_dates:
age_at = calculate_age(birthday, check_date)
print(f"Age on {check_date}: {age_at}")
# Multiple people
print("\nMultiple people:")
people = [
(date(1990, 3, 15), "Person 1"),
(date(1985, 7, 22), "Person 2"),
(date(2000, 11, 30), "Person 3")
]
for birth, name in people:
years, months, days = age_breakdown(birth, today)
print(f"{name} (born {birth}): {years}y {months}m {days}d")
# Age verification
def is_minimum_age(birthdate, current_date, min_age):
"""Check if person meets minimum age"""
return calculate_age(birthdate, current_date) >= min_age
print("\nAge verification:")
print("Is 18 or older?", is_minimum_age(birthday, today, 18))
print("Is 21 or older?", is_minimum_age(birthday, today, 21))
print("Is 65 or older?", is_minimum_age(birthday, today, 65))
# Age groups
def get_age_group(birthdate, current_date):
"""Get age group category"""
age = calculate_age(birthdate, current_date)
if age < 13:
return "Child"
elif age < 18:
return "Teenager"
elif age < 65:
return "Adult"
else:
return "Senior"
print("\nAge group:", get_age_group(birthday, today))
# Milestone birthdays
print("\nMilestone birthdays:")
milestones = [18, 21, 30, 40, 50, 65]
current_age = calculate_age(birthday, today)
for milestone in milestones:
if milestone > current_age:
milestone_date = date(birthday.year + milestone, birthday.month, birthday.day)
days_until_milestone = (milestone_date - today).days
print(f"{milestone} years: {milestone_date} (in {days_until_milestone} days)")
# Retirement
print("\nRetirement:")
retirement_age = 65
retirement_date = date(birthday.year + retirement_age, birthday.month, birthday.day)
years_to_retirement = calculate_age(today, retirement_date)
days_to_retirement = (retirement_date - today).days
print("Retirement date:", retirement_date)
if retirement_date > today:
print("Years to retirement:", years_to_retirement)
print("Days to retirement:", days_to_retirement)
else:
print("Already retired")
# Age calculation
from datetime import date, timedelta
# Age calculation
birthday = date(2000, 11, 30)
today = date(2025, 1, 29)
print("Birthdate:", birthday)
print("Today:", today)
print()
# Age in years (simple)
age_days = (today - birthday).days
age_years = age_days // 365
print("Age (simple):", age_years, "years")
# Age in years (accurate)
def calculate_age(birthdate, current_date):
"""Calculate age in years accounting for birthday"""
age = current_date.year - birthdate.year
# Check if birthday hasn't occurred yet this year
if current_date.month < birthdate.month or \
(current_date.month == birthdate.month and current_date.day < birthdate.day):
age -= 1
return age
age = calculate_age(birthday, today)
print("Age (accurate):", age, "years")
# Age breakdown
def age_breakdown(birthdate, current_date):
"""Calculate age in years, months, and days"""
years = calculate_age(birthdate, current_date)
# Calculate remaining months and days
if current_date.month >= birthdate.month:
months = current_date.month - birthdate.month
else:
months = 12 + current_date.month - birthdate.month
years -= 1
if current_date.day >= birthdate.day:
days = current_date.day - birthdate.day
else:
months -= 1
if months < 0:
months = 11
years -= 1
# Days in previous month
import calendar
prev_month = current_date.month - 1 if current_date.month > 1 else 12
prev_year = current_date.year if current_date.month > 1 else current_date.year - 1
days_in_prev = calendar.monthrange(prev_year, prev_month)[1]
days = days_in_prev - birthdate.day + current_date.day
return years, months, days
years, months, days = age_breakdown(birthday, today)
print(f"Age breakdown: {years} years, {months} months, {days} days")
# Age in different units
print("\nAge in different units:")
total_days = (today - birthday).days
print("Days:", total_days)
print("Weeks:", total_days // 7)
print("Months (approx):", total_days // 30)
print("Years (approx):", total_days // 365)
# Next birthday
def next_birthday(birthdate, current_date):
"""Calculate next birthday"""
next_bd = date(current_date.year, birthdate.month, birthdate.day)
if next_bd <= current_date:
next_bd = date(current_date.year + 1, birthdate.month, birthdate.day)
return next_bd
next_bd = next_birthday(birthday, today)
days_until = (next_bd - today).days
print("\nNext birthday:", next_bd)
print("Days until birthday:", days_until)
# Age at specific dates
print("\nAge at specific dates:")
check_dates = [
date(2020, 1, 1),
date(2025, 1, 1),
date(2030, 12, 31)
]
for check_date in check_dates:
age_at = calculate_age(birthday, check_date)
print(f"Age on {check_date}: {age_at}")
# Multiple people
print("\nMultiple people:")
people = [
(date(1990, 3, 15), "Person 1"),
(date(1985, 7, 22), "Person 2"),
(date(2000, 11, 30), "Person 3")
]
for birth, name in people:
years, months, days = age_breakdown(birth, today)
print(f"{name} (born {birth}): {years}y {months}m {days}d")
# Age verification
def is_minimum_age(birthdate, current_date, min_age):
"""Check if person meets minimum age"""
return calculate_age(birthdate, current_date) >= min_age
print("\nAge verification:")
print("Is 18 or older?", is_minimum_age(birthday, today, 18))
print("Is 21 or older?", is_minimum_age(birthday, today, 21))
print("Is 65 or older?", is_minimum_age(birthday, today, 65))
# Age groups
def get_age_group(birthdate, current_date):
"""Get age group category"""
age = calculate_age(birthdate, current_date)
if age < 13:
return "Child"
elif age < 18:
return "Teenager"
elif age < 65:
return "Adult"
else:
return "Senior"
print("\nAge group:", get_age_group(birthday, today))
# Milestone birthdays
print("\nMilestone birthdays:")
milestones = [18, 21, 30, 40, 50, 65]
current_age = calculate_age(birthday, today)
for milestone in milestones:
if milestone > current_age:
milestone_date = date(birthday.year + milestone, birthday.month, birthday.day)
days_until_milestone = (milestone_date - today).days
print(f"{milestone} years: {milestone_date} (in {days_until_milestone} days)")
# Retirement
print("\nRetirement:")
retirement_age = 65
retirement_date = date(birthday.year + retirement_age, birthday.month, birthday.day)
years_to_retirement = calculate_age(today, retirement_date)
days_to_retirement = (retirement_date - today).days
print("Retirement date:", retirement_date)
if retirement_date > today:
print("Years to retirement:", years_to_retirement)
print("Days to retirement:", days_to_retirement)
else:
print("Already retired")
birthday ← 1990-03-15, today ← 2025-01-29, age_days ← 12739, age_years ← 34
5# Age calculation6birthday→ 1990-03-15 = date(1990, 3, 15) #@birthday=date(1985, 7, 22), date(2000, 11, 30)7today→ 2025-01-29 = date(2025, 1, 29)89print("Birthdate:", birthday1990-03-15)10print("Today:", today2025-01-29)11print()1213# Age in years (simple)14age_days→ 12739 = (today - birthday).days1273915age_years→ 34 = age_days12739 // 36516print("Age (simple):", age_years34, "years")1718# Age in years (accurate)19def calculate_age(birthdate, current_date):20 """Calculate age in years accounting for birthday"""21 age = current_date.year - birthdate.year22 # Check if birthday hasn't occurred yet this year23 if current_date.month < birthdate.month or \24 (current_date.month == birthdate.month and current_date.day < birthdate.day):25 age -= 126 return age2728age = calculate_age(birthday1990-03-15, today2025-01-29)29print("Age (accurate):", age, "years")outputBirthdate: 1990-03-15 Today: 2025-01-29 Age (simple): 34 yearsage ← 35
pass 1 of 1418# Age in years (accurate)19def calculate_age(birthdate1990-03-15, current_date2025-01-29):20 """Calculate age in years accounting for birthday"""21 age→ 35 = current_date.year2025 - birthdate.year199022 # Check if birthday hasn't occurred yet this year14 passes — pass 1 is the card above pass birthdatecurrent_datecurrent_date.yearbirthdate.yearage1 1990-03-15 2025-01-29 2025 1990 35 2 1990-03-15 2025-01-29 2025 1990 35 3 1990-03-15 2020-01-01 2020 1990 30 4 1990-03-15 2025-01-01 2025 1990 35 5 1990-03-15 2030-12-31 2030 1990 40 6 1990-03-15 2025-01-29 2025 1990 35 7 1985-07-22 2025-01-29 2025 1985 40 8 2000-11-30 2025-01-29 2025 2000 25 9 1990-03-15 2025-01-29 2025 1990 35 ⋯ 3 more passes ⋯ 13 1990-03-15 2025-01-29 2025 1990 35 14 2025-01-29 2055-03-15 2055 2025 30 age ← 34
pass 1 of 1222# Check if birthday hasn't occurred yet this year23if current_date.month1 < birthdate.month3 or \24 (current_date.month1 == birthdate.month3 and current_date.day29 < birthdate.day15):25 age→ 34 -= 126return ageAll 12 passes — pass 1 is the card above pass birthdate.monthcurrent_date.daybirthdate.dayage1 3 29 15 35 → 34 2 3 29 15 35 → 34 3 3 1 15 30 → 29 4 3 1 15 35 → 34 5 3 29 15 35 → 34 6 7 29 22 40 → 39 7 11 29 30 25 → 24 8 3 29 15 35 → 34 9 3 29 15 35 → 34 10 3 29 15 35 → 34 11 3 29 15 35 → 34 12 3 29 15 35 → 34 return age
25 age -= 126return age34age ← 34
28age→ 34 = calculate_age(birthday1990-03-15, today2025-01-29)29print("Age (accurate):", age34, "years")3031# Age breakdown32def age_breakdown(birthdate, current_date):33 """Calculate age in years, months, and days"""34 years = calculate_age(birthdate, current_date)35 36 # Calculate remaining months and days37 if current_date.month >= birthdate.month:38 months = current_date.month - birthdate.month39 else:40 months = 12 + current_date.month - birthdate.month41 years -= 142 43 if current_date.day >= birthdate.day:44 days = current_date.day - birthdate.day45 else:46 months -= 147 if months < 0:48 months = 1149 years -= 150 # Days in previous month51 import calendar52 prev_month = current_date.month - 1 if current_date.month > 1 else 1253 prev_year = current_date.year if current_date.month > 1 else current_date.year - 154 days_in_prev = calendar.monthrange(prev_year, prev_month)[1]55 days = days_in_prev - birthdate.day + current_date.day56 57 return years, months, days5859years, months, days = age_breakdown(birthday1990-03-15, today2025-01-29)60print(f"Age breakdown: {years} years, {months} months, {days} days")outputAge (accurate): 34 yearsdef age_breakdown(birthdate, current_date):
pass 1 of 431# Age breakdown32def age_breakdown(birthdate1990-03-15, current_date2025-01-29):33 """Calculate age in years, months, and days"""34 years = calculate_age(birthdate1990-03-15, current_date2025-01-29)All 4 passes — pass 1 is the card above pass birthdate1 1990-03-15 2 1990-03-15 3 1985-07-22 4 2000-11-30 return age
25 age -= 126return age34years ← 34
33"""Calculate age in years, months, and days"""34years→ 34 = calculate_age(birthdate1990-03-15, current_date2025-01-29)months ← 10, years ← 33
pass 1 of 437if current_date.month >= birthdate.month:38 months = current_date.month - birthdate.month39else:40 months→ 10 = 12 + current_date.month1 - birthdate.month341 years→ 33 -= 1All 4 passes — pass 1 is the card above pass birthdate.monthcurrent_date.yearcalendarbirthdate.daycurrent_date.daymonthsyearsprev_monthprev_yeardays_in_prevdays1 3 — — — — 10 34 → 33 — — — — 2 3 — — — — 10 34 → 33 — — — — 3 7 — — — — 6 39 → 38 — — — — 4 11 2025 <module 'calendar' from '/usr/local/lib/python3.12/calendar.py'> 30 29 2 24 → 23 12 2024 31 30 days ← 14
pass 1 of 343if current_date.day29 >= birthdate.day15:44 days→ 14 = current_date.day29 - birthdate.day1545else:All 3 passes — pass 1 is the card above pass birthdate.daydays1 15 14 2 15 14 3 22 7 return years, months, days
57return years33, months10, days14years ← 33, months ← 10, days ← 14, total_days ← 12739
59years→ 33, months→ 10, days→ 14 = age_breakdown(birthday1990-03-15, today2025-01-29)60print(f"Age breakdown: {years33} years, {months10} months, {days14} days")6162# Age in different units63print("\nAge in different units:")64total_days→ 12739 = (today - birthday).days1273965print("Days:", total_days12739)66print("Weeks:", total_days12739 // 7)67print("Months (approx):", total_days12739 // 30)68print("Years (approx):", total_days12739 // 365)6970# Next birthday71def next_birthday(birthdate, current_date):72 """Calculate next birthday"""73 next_bd = date(current_date.year, birthdate.month, birthdate.day)74 if next_bd <= current_date:75 next_bd = date(current_date.year + 1, birthdate.month, birthdate.day)76 return next_bd7778next_bd = next_birthday(birthday1990-03-15, today2025-01-29)79days_until = (next_bd - today).daysoutputAge breakdown: 33 years, 10 months, 14 days Age in different units: Days: 12739 Weeks: 1819 Months (approx): 424 Years (approx): 34next_bd ← 2025-03-15
70# Next birthday71def next_birthday(birthdate1990-03-15, current_date2025-01-29):72 """Calculate next birthday"""73 next_bd→ 2025-03-15 = date(current_date.year2025, birthdate.month3, birthdate.day15)74 if next_bd <= current_date:75 next_bd = date(current_date.year + 1, birthdate.month, birthdate.day)76 return next_bd2025-03-15next_bd ← 2025-03-15, days_until ← 45, check_dates ← [datetime.date(2020, 1, 1), datetime.date(2025, 1, 1), datetime.date(2030, 12, 31)]
78next_bd→ 2025-03-15 = next_birthday(birthday1990-03-15, today2025-01-29)79days_until→ 45 = (next_bd - today).days4580print("\nNext birthday:", next_bd2025-03-15)81print("Days until birthday:", days_until45)8283# Age at specific dates84print("\nAge at specific dates:")85check_dates→ [datetime.date(2020, 1, 1), datetime.date(2025, 1, 1), datetime.date(2030, 12, 31)] = [86 date(2020, 1, 1),87 date(2025, 1, 1),88 date(2030, 12, 31)89]output Next birthday: 2025-03-15 Days until birthday: 45 Age at specific dates:for check_date in check_dates:
pass 1 of 391for check_date2020-01-01 in check_dates[datetime.date(2020, 1, 1), datetime.date(2025, 1, 1), datetime.date(2030, 12, 31)]:92 age_at = calculate_age(birthday1990-03-15, check_date2020-01-01)93 print(f"Age on {check_date}: {age_at}")All 3 passes — pass 1 is the card above pass check_date1 2020-01-01 2 2025-01-01 3 2030-12-31 return age
25 age -= 126return age29age_at ← 29
91for check_date in check_dates:92 age_at→ 29 = calculate_age(birthday1990-03-15, check_date2020-01-01)93 print(f"Age on {check_date2020-01-01}: {age_at29}")outputAge on 2020-01-01: 29return age
25 age -= 126return age34age_at ← 34
91for check_date in check_dates:92 age_at→ 34 = calculate_age(birthday1990-03-15, check_date2025-01-01)93 print(f"Age on {check_date2025-01-01}: {age_at34}")outputAge on 2025-01-01: 34age_at ← 40
91for check_date in check_dates:92 age_at→ 40 = calculate_age(birthday1990-03-15, check_date2030-12-31)93 print(f"Age on {check_date2030-12-31}: {age_at40}")outputAge on 2030-12-31: 40people ← [(datetime.date(1990, 3, 15), 'Person 1'), (datetime.date(1985, 7, 22), 'Person 2'), (datetime.date(2000, 11, 30), 'Person 3')]
95# Multiple people96print("\nMultiple people:")97people→ [(datetime.date(1990, 3, 15), 'Person 1'), (datetime.date(1985, 7, 22), 'Person 2'), (datetime.date(2000, 11, 30), 'Person 3')] = [98 (date(1990, 3, 15), "Person 1"),99 (date(1985, 7, 22), "Person 2"),100 (date(2000, 11, 30), "Person 3")101]output Multiple people:for birth, name in people:
pass 1 of 3103for birth1990-03-15, namePerson 1 in people[(datetime.date(1990, 3, 15), 'Person 1'), (datetime.date(1985, 7, 22), 'Person 2'), (datetime.date(2000, 11, 30), 'Person 3')]:104 years, months, days = age_breakdown(birth1990-03-15, today2025-01-29)105 print(f"{name} (born {birth}): {years}y {months}m {days}d")All 3 passes — pass 1 is the card above pass birthname1 1990-03-15 Person 1 2 1985-07-22 Person 2 3 2000-11-30 Person 3 return age
25 age -= 126return age34years ← 34
33"""Calculate age in years, months, and days"""34years→ 34 = calculate_age(birthdate1990-03-15, current_date2025-01-29)return years, months, days
57return years33, months10, days14years ← 33, months ← 10, days ← 14
103for birth, name in people:104 years→ 33, months→ 10, days→ 14 = age_breakdown(birth1990-03-15, today2025-01-29)105 print(f"{namePerson 1} (born {birth1990-03-15}): {years33}y {months10}m {days14}d")outputPerson 1 (born 1990-03-15): 33y 10m 14dreturn age
25 age -= 126return age39years ← 39
33"""Calculate age in years, months, and days"""34years→ 39 = calculate_age(birthdate1985-07-22, current_date2025-01-29)return years, months, days
57return years38, months6, days7years ← 38, months ← 6, days ← 7
103for birth, name in people:104 years→ 38, months→ 6, days→ 7 = age_breakdown(birth1985-07-22, today2025-01-29)105 print(f"{namePerson 2} (born {birth1985-07-22}): {years38}y {months6}m {days7}d")outputPerson 2 (born 1985-07-22): 38y 6m 7dreturn age
25 age -= 126return age24years ← 24
33"""Calculate age in years, months, and days"""34years→ 24 = calculate_age(birthdate2000-11-30, current_date2025-01-29)months ← 1, prev_month ← 12, prev_year ← 2024, days_in_prev ← 31
43if current_date.day >= birthdate.day:44 days = current_date.day - birthdate.day45else:46 months→ 1 -= 147 if months < 0:48 months = 1149 years -= 150 # Days in previous month51 import calendar52 prev_month→ 12 = current_date.month1 - 1 if current_date.month > 1 else 1253 prev_year→ 2024 = current_date.year2025 if current_date.month1 > 1 else current_date.year - 154 days_in_prev→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(prev_year2024, prev_month12)[1]55 days→ 30 = days_in_prev31 - birthdate.day30 + current_date.day29return years, months, days
57return years23, months1, days30years ← 23, months ← 1, days ← 30
103for birth, name in people:104 years→ 23, months→ 1, days→ 30 = age_breakdown(birth2000-11-30, today2025-01-29)105 print(f"{namePerson 3} (born {birth2000-11-30}): {years23}y {months1}m {days30}d")outputPerson 3 (born 2000-11-30): 23y 1m 30dprint("Is 18 or older?", is_minimum_age(birthday, today, 18))
112print("\nAge verification:")113print("Is 18 or older?", is_minimum_age(birthday1990-03-15, today2025-01-29, 18))114print("Is 21 or older?", is_minimum_age(birthday, today, 21))output Age verification:def is_minimum_age(birthdate, current_date, min_age):
pass 1 of 3107# Age verification108def is_minimum_age(birthdate1990-03-15, current_date2025-01-29, min_age18):109 """Check if person meets minimum age"""110 return calculate_age(birthdate1990-03-15, current_date2025-01-29) >= min_age18All 3 passes — pass 1 is the card above pass min_age1 18 2 21 3 65 return age
25 age -= 126return age34print("Is 18 or older?", is_minimum_age(birthday, today, 18))
112print("\nAge verification:")113print("Is 18 or older?", is_minimum_age(birthday1990-03-15, today2025-01-29, 18))114print("Is 21 or older?", is_minimum_age(birthday1990-03-15, today2025-01-29, 21))115print("Is 65 or older?", is_minimum_age(birthday, today, 65))outputIs 18 or older? Truereturn age
25 age -= 126return age34print("Is 21 or older?", is_minimum_age(birthday, today, 21))
113print("Is 18 or older?", is_minimum_age(birthday, today, 18))114print("Is 21 or older?", is_minimum_age(birthday1990-03-15, today2025-01-29, 21))115print("Is 65 or older?", is_minimum_age(birthday1990-03-15, today2025-01-29, 65))outputIs 21 or older? Truereturn age
25 age -= 126return age34print("Is 65 or older?", is_minimum_age(birthday, today, 65))
114print("Is 21 or older?", is_minimum_age(birthday, today, 21))115print("Is 65 or older?", is_minimum_age(birthday1990-03-15, today2025-01-29, 65))116117# Age groups118def get_age_group(birthdate, current_date):119 """Get age group category"""120 age = calculate_age(birthdate, current_date)121 if age < 13:122 return "Child"123 elif age < 18:124 return "Teenager"125 elif age < 65:126 return "Adult"127 else:128 return "Senior"129130print("\nAge group:", get_age_group(birthday1990-03-15, today2025-01-29))outputIs 65 or older? Falsedef get_age_group(birthdate, current_date):
117# Age groups118def get_age_group(birthdate1990-03-15, current_date2025-01-29):119 """Get age group category"""120 age = calculate_age(birthdate1990-03-15, current_date2025-01-29)121 if age < 13:return age
25 age -= 126return age34age ← 34
119"""Get age group category"""120age→ 34 = calculate_age(birthdate1990-03-15, current_date2025-01-29)121if age < 13:elif age < 65:
124 return "Teenager"125elif age34 < 65:126 return "Adult"127else:milestones ← [18, 21, 30, 40, 50, 65]
130print("\nAge group:", get_age_group(birthday1990-03-15, today2025-01-29))131132# Milestone birthdays133print("\nMilestone birthdays:")134milestones→ [18, 21, 30, 40, 50, 65] = [18, 21, 30, 40, 50, 65]135current_age = calculate_age(birthday1990-03-15, today2025-01-29)output Age group: Adult Milestone birthdays:return age
25 age -= 126return age34current_age ← 34
134milestones = [18, 21, 30, 40, 50, 65]135current_age→ 34 = calculate_age(birthday1990-03-15, today2025-01-29)for milestone in milestones:
pass 1 of 6137for milestone18 in milestones[18, 21, 30, 40, 50, 65]:138 if milestone > current_age:139 milestone_date = date(birthday.year + milestone, birthday.month, birthday.day)All 6 passes — pass 1 is the card above pass milestone1 18 2 21 3 30 4 40 5 50 6 65 milestone_date ← 2030-03-15, days_until_milestone ← 1871
pass 1 of 3137for milestone in milestones:138 if milestone40 > current_age34:139 milestone_date→ 2030-03-15 = date(birthday.year1990 + milestone40, birthday.month3, birthday.day15)140 days_until_milestone→ 1871 = (milestone_date - today).days1871141 print(f"{milestone40} years: {milestone_date2030-03-15} (in {days_until_milestone1871} days)")output40 years: 2030-03-15 (in 1871 days)All 3 passes — pass 1 is the card above pass milestone(milestone_date - today).daysmilestone_datedays_until_milestone1 40 1871 2030-03-15 1871 2 50 5524 2040-03-15 5524 3 65 11002 2055-03-15 11002 retirement_age ← 65, retirement_date ← 2055-03-15
143# Retirement144print("\nRetirement:")145retirement_age→ 65 = 65146retirement_date→ 2055-03-15 = date(birthday.year1990 + retirement_age65, birthday.month3, birthday.day15)147years_to_retirement = calculate_age(today2025-01-29, retirement_date2055-03-15)148days_to_retirement = (retirement_date - today).daysoutput Retirement:years_to_retirement ← 30, days_to_retirement ← 11002
146retirement_date = date(birthday.year + retirement_age, birthday.month, birthday.day)147years_to_retirement→ 30 = calculate_age(today2025-01-29, retirement_date2055-03-15)148days_to_retirement→ 11002 = (retirement_date - today).days11002149150print("Retirement date:", retirement_date2055-03-15)151if retirement_date > today:outputRetirement date: 2055-03-15if retirement_date > today:
150print("Retirement date:", retirement_date)151if retirement_date2055-03-15 > today2025-01-29:152 print("Years to retirement:", years_to_retirement30)153 print("Days to retirement:", days_to_retirement11002)154else:outputYears to retirement: 30 Days to retirement: 11002
birthday ← 1985-07-22, today ← 2025-01-29, age_days ← 14436, age_years ← 39
5# Age calculation6birthday→ 1985-07-22 = date(1985, 7, 22)7today→ 2025-01-29 = date(2025, 1, 29)89print("Birthdate:", birthday1985-07-22)10print("Today:", today2025-01-29)11print()1213# Age in years (simple)14age_days→ 14436 = (today - birthday).days1443615age_years→ 39 = age_days14436 // 36516print("Age (simple):", age_years39, "years")1718# Age in years (accurate)19def calculate_age(birthdate, current_date):20 """Calculate age in years accounting for birthday"""21 age = current_date.year - birthdate.year22 # Check if birthday hasn't occurred yet this year23 if current_date.month < birthdate.month or \24 (current_date.month == birthdate.month and current_date.day < birthdate.day):25 age -= 126 return age2728age = calculate_age(birthday1985-07-22, today2025-01-29)29print("Age (accurate):", age, "years")outputBirthdate: 1985-07-22 Today: 2025-01-29 Age (simple): 39 yearsage ← 40
pass 1 of 1418# Age in years (accurate)19def calculate_age(birthdate1985-07-22, current_date2025-01-29):20 """Calculate age in years accounting for birthday"""21 age→ 40 = current_date.year2025 - birthdate.year198522 # Check if birthday hasn't occurred yet this year14 passes — pass 1 is the card above pass birthdatecurrent_datecurrent_date.yearbirthdate.yearage1 1985-07-22 2025-01-29 2025 1985 40 2 1985-07-22 2025-01-29 2025 1985 40 3 1985-07-22 2020-01-01 2020 1985 35 4 1985-07-22 2025-01-01 2025 1985 40 5 1985-07-22 2030-12-31 2030 1985 45 6 1990-03-15 2025-01-29 2025 1990 35 7 1985-07-22 2025-01-29 2025 1985 40 8 2000-11-30 2025-01-29 2025 2000 25 9 1985-07-22 2025-01-29 2025 1985 40 ⋯ 3 more passes ⋯ 13 1985-07-22 2025-01-29 2025 1985 40 14 2025-01-29 2050-07-22 2050 2025 25 age ← 39
pass 1 of 1222# Check if birthday hasn't occurred yet this year23if current_date.month1 < birthdate.month7 or \24 (current_date.month1 == birthdate.month7 and current_date.day29 < birthdate.day22):25 age→ 39 -= 126return ageAll 12 passes — pass 1 is the card above pass birthdate.monthcurrent_date.daybirthdate.dayage1 7 29 22 40 → 39 2 7 29 22 40 → 39 3 7 1 22 35 → 34 4 7 1 22 40 → 39 5 3 29 15 35 → 34 6 7 29 22 40 → 39 7 11 29 30 25 → 24 8 7 29 22 40 → 39 9 7 29 22 40 → 39 10 7 29 22 40 → 39 11 7 29 22 40 → 39 12 7 29 22 40 → 39 return age
25 age -= 126return age39age ← 39
28age→ 39 = calculate_age(birthday1985-07-22, today2025-01-29)29print("Age (accurate):", age39, "years")3031# Age breakdown32def age_breakdown(birthdate, current_date):33 """Calculate age in years, months, and days"""34 years = calculate_age(birthdate, current_date)35 36 # Calculate remaining months and days37 if current_date.month >= birthdate.month:38 months = current_date.month - birthdate.month39 else:40 months = 12 + current_date.month - birthdate.month41 years -= 142 43 if current_date.day >= birthdate.day:44 days = current_date.day - birthdate.day45 else:46 months -= 147 if months < 0:48 months = 1149 years -= 150 # Days in previous month51 import calendar52 prev_month = current_date.month - 1 if current_date.month > 1 else 1253 prev_year = current_date.year if current_date.month > 1 else current_date.year - 154 days_in_prev = calendar.monthrange(prev_year, prev_month)[1]55 days = days_in_prev - birthdate.day + current_date.day56 57 return years, months, days5859years, months, days = age_breakdown(birthday1985-07-22, today2025-01-29)60print(f"Age breakdown: {years} years, {months} months, {days} days")outputAge (accurate): 39 yearsdef age_breakdown(birthdate, current_date):
pass 1 of 431# Age breakdown32def age_breakdown(birthdate1985-07-22, current_date2025-01-29):33 """Calculate age in years, months, and days"""34 years = calculate_age(birthdate1985-07-22, current_date2025-01-29)All 4 passes — pass 1 is the card above pass birthdate1 1985-07-22 2 1990-03-15 3 1985-07-22 4 2000-11-30 return age
25 age -= 126return age39years ← 39
33"""Calculate age in years, months, and days"""34years→ 39 = calculate_age(birthdate1985-07-22, current_date2025-01-29)months ← 6, years ← 38
pass 1 of 437if current_date.month >= birthdate.month:38 months = current_date.month - birthdate.month39else:40 months→ 6 = 12 + current_date.month1 - birthdate.month741 years→ 38 -= 1All 4 passes — pass 1 is the card above pass birthdate.monthcurrent_date.yearcalendarbirthdate.daycurrent_date.daymonthsyearsprev_monthprev_yeardays_in_prevdays1 7 — — — — 6 39 → 38 — — — — 2 3 — — — — 10 34 → 33 — — — — 3 7 — — — — 6 39 → 38 — — — — 4 11 2025 <module 'calendar' from '/usr/local/lib/python3.12/calendar.py'> 30 29 2 24 → 23 12 2024 31 30 days ← 7
pass 1 of 343if current_date.day29 >= birthdate.day22:44 days→ 7 = current_date.day29 - birthdate.day2245else:All 3 passes — pass 1 is the card above pass birthdate.daydays1 22 7 2 15 14 3 22 7 return years, months, days
57return years38, months6, days7years ← 38, months ← 6, days ← 7, total_days ← 14436
59years→ 38, months→ 6, days→ 7 = age_breakdown(birthday1985-07-22, today2025-01-29)60print(f"Age breakdown: {years38} years, {months6} months, {days7} days")6162# Age in different units63print("\nAge in different units:")64total_days→ 14436 = (today - birthday).days1443665print("Days:", total_days14436)66print("Weeks:", total_days14436 // 7)67print("Months (approx):", total_days14436 // 30)68print("Years (approx):", total_days14436 // 365)6970# Next birthday71def next_birthday(birthdate, current_date):72 """Calculate next birthday"""73 next_bd = date(current_date.year, birthdate.month, birthdate.day)74 if next_bd <= current_date:75 next_bd = date(current_date.year + 1, birthdate.month, birthdate.day)76 return next_bd7778next_bd = next_birthday(birthday1985-07-22, today2025-01-29)79days_until = (next_bd - today).daysoutputAge breakdown: 38 years, 6 months, 7 days Age in different units: Days: 14436 Weeks: 2062 Months (approx): 481 Years (approx): 39next_bd ← 2025-07-22
70# Next birthday71def next_birthday(birthdate1985-07-22, current_date2025-01-29):72 """Calculate next birthday"""73 next_bd→ 2025-07-22 = date(current_date.year2025, birthdate.month7, birthdate.day22)74 if next_bd <= current_date:75 next_bd = date(current_date.year + 1, birthdate.month, birthdate.day)76 return next_bd2025-07-22next_bd ← 2025-07-22, days_until ← 174, check_dates ← [datetime.date(2020, 1, 1), datetime.date(2025, 1, 1), datetime.date(2030, 12, 31)]
78next_bd→ 2025-07-22 = next_birthday(birthday1985-07-22, today2025-01-29)79days_until→ 174 = (next_bd - today).days17480print("\nNext birthday:", next_bd2025-07-22)81print("Days until birthday:", days_until174)8283# Age at specific dates84print("\nAge at specific dates:")85check_dates→ [datetime.date(2020, 1, 1), datetime.date(2025, 1, 1), datetime.date(2030, 12, 31)] = [86 date(2020, 1, 1),87 date(2025, 1, 1),88 date(2030, 12, 31)89]output Next birthday: 2025-07-22 Days until birthday: 174 Age at specific dates:for check_date in check_dates:
pass 1 of 391for check_date2020-01-01 in check_dates[datetime.date(2020, 1, 1), datetime.date(2025, 1, 1), datetime.date(2030, 12, 31)]:92 age_at = calculate_age(birthday1985-07-22, check_date2020-01-01)93 print(f"Age on {check_date}: {age_at}")All 3 passes — pass 1 is the card above pass check_date1 2020-01-01 2 2025-01-01 3 2030-12-31 return age
25 age -= 126return age34age_at ← 34
91for check_date in check_dates:92 age_at→ 34 = calculate_age(birthday1985-07-22, check_date2020-01-01)93 print(f"Age on {check_date2020-01-01}: {age_at34}")outputAge on 2020-01-01: 34return age
25 age -= 126return age39age_at ← 39
91for check_date in check_dates:92 age_at→ 39 = calculate_age(birthday1985-07-22, check_date2025-01-01)93 print(f"Age on {check_date2025-01-01}: {age_at39}")outputAge on 2025-01-01: 39age_at ← 45
91for check_date in check_dates:92 age_at→ 45 = calculate_age(birthday1985-07-22, check_date2030-12-31)93 print(f"Age on {check_date2030-12-31}: {age_at45}")outputAge on 2030-12-31: 45people ← [(datetime.date(1990, 3, 15), 'Person 1'), (datetime.date(1985, 7, 22), 'Person 2'), (datetime.date(2000, 11, 30), 'Person 3')]
95# Multiple people96print("\nMultiple people:")97people→ [(datetime.date(1990, 3, 15), 'Person 1'), (datetime.date(1985, 7, 22), 'Person 2'), (datetime.date(2000, 11, 30), 'Person 3')] = [98 (date(1990, 3, 15), "Person 1"),99 (date(1985, 7, 22), "Person 2"),100 (date(2000, 11, 30), "Person 3")101]output Multiple people:for birth, name in people:
pass 1 of 3103for birth1990-03-15, namePerson 1 in people[(datetime.date(1990, 3, 15), 'Person 1'), (datetime.date(1985, 7, 22), 'Person 2'), (datetime.date(2000, 11, 30), 'Person 3')]:104 years, months, days = age_breakdown(birth1990-03-15, today2025-01-29)105 print(f"{name} (born {birth}): {years}y {months}m {days}d")All 3 passes — pass 1 is the card above pass birthname1 1990-03-15 Person 1 2 1985-07-22 Person 2 3 2000-11-30 Person 3 return age
25 age -= 126return age34years ← 34
33"""Calculate age in years, months, and days"""34years→ 34 = calculate_age(birthdate1990-03-15, current_date2025-01-29)return years, months, days
57return years33, months10, days14years ← 33, months ← 10, days ← 14
103for birth, name in people:104 years→ 33, months→ 10, days→ 14 = age_breakdown(birth1990-03-15, today2025-01-29)105 print(f"{namePerson 1} (born {birth1990-03-15}): {years33}y {months10}m {days14}d")outputPerson 1 (born 1990-03-15): 33y 10m 14dreturn age
25 age -= 126return age39years ← 39
33"""Calculate age in years, months, and days"""34years→ 39 = calculate_age(birthdate1985-07-22, current_date2025-01-29)return years, months, days
57return years38, months6, days7years ← 38, months ← 6, days ← 7
103for birth, name in people:104 years→ 38, months→ 6, days→ 7 = age_breakdown(birth1985-07-22, today2025-01-29)105 print(f"{namePerson 2} (born {birth1985-07-22}): {years38}y {months6}m {days7}d")outputPerson 2 (born 1985-07-22): 38y 6m 7dreturn age
25 age -= 126return age24years ← 24
33"""Calculate age in years, months, and days"""34years→ 24 = calculate_age(birthdate2000-11-30, current_date2025-01-29)months ← 1, prev_month ← 12, prev_year ← 2024, days_in_prev ← 31
43if current_date.day >= birthdate.day:44 days = current_date.day - birthdate.day45else:46 months→ 1 -= 147 if months < 0:48 months = 1149 years -= 150 # Days in previous month51 import calendar52 prev_month→ 12 = current_date.month1 - 1 if current_date.month > 1 else 1253 prev_year→ 2024 = current_date.year2025 if current_date.month1 > 1 else current_date.year - 154 days_in_prev→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(prev_year2024, prev_month12)[1]55 days→ 30 = days_in_prev31 - birthdate.day30 + current_date.day29return years, months, days
57return years23, months1, days30years ← 23, months ← 1, days ← 30
103for birth, name in people:104 years→ 23, months→ 1, days→ 30 = age_breakdown(birth2000-11-30, today2025-01-29)105 print(f"{namePerson 3} (born {birth2000-11-30}): {years23}y {months1}m {days30}d")outputPerson 3 (born 2000-11-30): 23y 1m 30dprint("Is 18 or older?", is_minimum_age(birthday, today, 18))
112print("\nAge verification:")113print("Is 18 or older?", is_minimum_age(birthday1985-07-22, today2025-01-29, 18))114print("Is 21 or older?", is_minimum_age(birthday, today, 21))output Age verification:def is_minimum_age(birthdate, current_date, min_age):
pass 1 of 3107# Age verification108def is_minimum_age(birthdate1985-07-22, current_date2025-01-29, min_age18):109 """Check if person meets minimum age"""110 return calculate_age(birthdate1985-07-22, current_date2025-01-29) >= min_age18All 3 passes — pass 1 is the card above pass min_age1 18 2 21 3 65 return age
25 age -= 126return age39print("Is 18 or older?", is_minimum_age(birthday, today, 18))
112print("\nAge verification:")113print("Is 18 or older?", is_minimum_age(birthday1985-07-22, today2025-01-29, 18))114print("Is 21 or older?", is_minimum_age(birthday1985-07-22, today2025-01-29, 21))115print("Is 65 or older?", is_minimum_age(birthday, today, 65))outputIs 18 or older? Truereturn age
25 age -= 126return age39print("Is 21 or older?", is_minimum_age(birthday, today, 21))
113print("Is 18 or older?", is_minimum_age(birthday, today, 18))114print("Is 21 or older?", is_minimum_age(birthday1985-07-22, today2025-01-29, 21))115print("Is 65 or older?", is_minimum_age(birthday1985-07-22, today2025-01-29, 65))outputIs 21 or older? Truereturn age
25 age -= 126return age39print("Is 65 or older?", is_minimum_age(birthday, today, 65))
114print("Is 21 or older?", is_minimum_age(birthday, today, 21))115print("Is 65 or older?", is_minimum_age(birthday1985-07-22, today2025-01-29, 65))116117# Age groups118def get_age_group(birthdate, current_date):119 """Get age group category"""120 age = calculate_age(birthdate, current_date)121 if age < 13:122 return "Child"123 elif age < 18:124 return "Teenager"125 elif age < 65:126 return "Adult"127 else:128 return "Senior"129130print("\nAge group:", get_age_group(birthday1985-07-22, today2025-01-29))outputIs 65 or older? Falsedef get_age_group(birthdate, current_date):
117# Age groups118def get_age_group(birthdate1985-07-22, current_date2025-01-29):119 """Get age group category"""120 age = calculate_age(birthdate1985-07-22, current_date2025-01-29)121 if age < 13:return age
25 age -= 126return age39age ← 39
119"""Get age group category"""120age→ 39 = calculate_age(birthdate1985-07-22, current_date2025-01-29)121if age < 13:elif age < 65:
124 return "Teenager"125elif age39 < 65:126 return "Adult"127else:milestones ← [18, 21, 30, 40, 50, 65]
130print("\nAge group:", get_age_group(birthday1985-07-22, today2025-01-29))131132# Milestone birthdays133print("\nMilestone birthdays:")134milestones→ [18, 21, 30, 40, 50, 65] = [18, 21, 30, 40, 50, 65]135current_age = calculate_age(birthday1985-07-22, today2025-01-29)output Age group: Adult Milestone birthdays:return age
25 age -= 126return age39current_age ← 39
134milestones = [18, 21, 30, 40, 50, 65]135current_age→ 39 = calculate_age(birthday1985-07-22, today2025-01-29)for milestone in milestones:
pass 1 of 6137for milestone18 in milestones[18, 21, 30, 40, 50, 65]:138 if milestone > current_age:139 milestone_date = date(birthday.year + milestone, birthday.month, birthday.day)All 6 passes — pass 1 is the card above pass milestone1 18 2 21 3 30 4 40 5 50 6 65 milestone_date ← 2025-07-22, days_until_milestone ← 174
pass 1 of 3137for milestone in milestones:138 if milestone40 > current_age39:139 milestone_date→ 2025-07-22 = date(birthday.year1985 + milestone40, birthday.month7, birthday.day22)140 days_until_milestone→ 174 = (milestone_date - today).days174141 print(f"{milestone40} years: {milestone_date2025-07-22} (in {days_until_milestone174} days)")output40 years: 2025-07-22 (in 174 days)All 3 passes — pass 1 is the card above pass milestone(milestone_date - today).daysmilestone_datedays_until_milestone1 40 174 2025-07-22 174 2 50 3826 2035-07-22 3826 3 65 9305 2050-07-22 9305 retirement_age ← 65, retirement_date ← 2050-07-22
143# Retirement144print("\nRetirement:")145retirement_age→ 65 = 65146retirement_date→ 2050-07-22 = date(birthday.year1985 + retirement_age65, birthday.month7, birthday.day22)147years_to_retirement = calculate_age(today2025-01-29, retirement_date2050-07-22)148days_to_retirement = (retirement_date - today).daysoutput Retirement:years_to_retirement ← 25, days_to_retirement ← 9305
146retirement_date = date(birthday.year + retirement_age, birthday.month, birthday.day)147years_to_retirement→ 25 = calculate_age(today2025-01-29, retirement_date2050-07-22)148days_to_retirement→ 9305 = (retirement_date - today).days9305149150print("Retirement date:", retirement_date2050-07-22)151if retirement_date > today:outputRetirement date: 2050-07-22if retirement_date > today:
150print("Retirement date:", retirement_date)151if retirement_date2050-07-22 > today2025-01-29:152 print("Years to retirement:", years_to_retirement25)153 print("Days to retirement:", days_to_retirement9305)154else:outputYears to retirement: 25 Days to retirement: 9305
birthday ← 2000-11-30, today ← 2025-01-29, age_days ← 8826, age_years ← 24
5# Age calculation6birthday→ 2000-11-30 = date(2000, 11, 30)7today→ 2025-01-29 = date(2025, 1, 29)89print("Birthdate:", birthday2000-11-30)10print("Today:", today2025-01-29)11print()1213# Age in years (simple)14age_days→ 8826 = (today - birthday).days882615age_years→ 24 = age_days8826 // 36516print("Age (simple):", age_years24, "years")1718# Age in years (accurate)19def calculate_age(birthdate, current_date):20 """Calculate age in years accounting for birthday"""21 age = current_date.year - birthdate.year22 # Check if birthday hasn't occurred yet this year23 if current_date.month < birthdate.month or \24 (current_date.month == birthdate.month and current_date.day < birthdate.day):25 age -= 126 return age2728age = calculate_age(birthday2000-11-30, today2025-01-29)29print("Age (accurate):", age, "years")outputBirthdate: 2000-11-30 Today: 2025-01-29 Age (simple): 24 yearsage ← 25
pass 1 of 1418# Age in years (accurate)19def calculate_age(birthdate2000-11-30, current_date2025-01-29):20 """Calculate age in years accounting for birthday"""21 age→ 25 = current_date.year2025 - birthdate.year200022 # Check if birthday hasn't occurred yet this year14 passes — pass 1 is the card above pass birthdatecurrent_datecurrent_date.yearbirthdate.yearage1 2000-11-30 2025-01-29 2025 2000 25 2 2000-11-30 2025-01-29 2025 2000 25 3 2000-11-30 2020-01-01 2020 2000 20 4 2000-11-30 2025-01-01 2025 2000 25 5 2000-11-30 2030-12-31 2030 2000 30 6 1990-03-15 2025-01-29 2025 1990 35 7 1985-07-22 2025-01-29 2025 1985 40 8 2000-11-30 2025-01-29 2025 2000 25 9 2000-11-30 2025-01-29 2025 2000 25 ⋯ 3 more passes ⋯ 13 2000-11-30 2025-01-29 2025 2000 25 14 2025-01-29 2065-11-30 2065 2025 40 age ← 24
pass 1 of 1222# Check if birthday hasn't occurred yet this year23if current_date.month1 < birthdate.month11 or \24 (current_date.month1 == birthdate.month11 and current_date.day29 < birthdate.day30):25 age→ 24 -= 126return ageAll 12 passes — pass 1 is the card above pass birthdate.monthcurrent_date.daybirthdate.dayage1 11 29 30 25 → 24 2 11 29 30 25 → 24 3 11 1 30 20 → 19 4 11 1 30 25 → 24 5 3 29 15 35 → 34 6 7 29 22 40 → 39 7 11 29 30 25 → 24 8 11 29 30 25 → 24 9 11 29 30 25 → 24 10 11 29 30 25 → 24 11 11 29 30 25 → 24 12 11 29 30 25 → 24 return age
25 age -= 126return age24age ← 24
28age→ 24 = calculate_age(birthday2000-11-30, today2025-01-29)29print("Age (accurate):", age24, "years")3031# Age breakdown32def age_breakdown(birthdate, current_date):33 """Calculate age in years, months, and days"""34 years = calculate_age(birthdate, current_date)35 36 # Calculate remaining months and days37 if current_date.month >= birthdate.month:38 months = current_date.month - birthdate.month39 else:40 months = 12 + current_date.month - birthdate.month41 years -= 142 43 if current_date.day >= birthdate.day:44 days = current_date.day - birthdate.day45 else:46 months -= 147 if months < 0:48 months = 1149 years -= 150 # Days in previous month51 import calendar52 prev_month = current_date.month - 1 if current_date.month > 1 else 1253 prev_year = current_date.year if current_date.month > 1 else current_date.year - 154 days_in_prev = calendar.monthrange(prev_year, prev_month)[1]55 days = days_in_prev - birthdate.day + current_date.day56 57 return years, months, days5859years, months, days = age_breakdown(birthday2000-11-30, today2025-01-29)60print(f"Age breakdown: {years} years, {months} months, {days} days")outputAge (accurate): 24 yearsdef age_breakdown(birthdate, current_date):
pass 1 of 431# Age breakdown32def age_breakdown(birthdate2000-11-30, current_date2025-01-29):33 """Calculate age in years, months, and days"""34 years = calculate_age(birthdate2000-11-30, current_date2025-01-29)All 4 passes — pass 1 is the card above pass birthdate1 2000-11-30 2 1990-03-15 3 1985-07-22 4 2000-11-30 return age
25 age -= 126return age24years ← 24
33"""Calculate age in years, months, and days"""34years→ 24 = calculate_age(birthdate2000-11-30, current_date2025-01-29)months ← 2, years ← 23
pass 1 of 437if current_date.month >= birthdate.month:38 months = current_date.month - birthdate.month39else:40 months→ 2 = 12 + current_date.month1 - birthdate.month1141 years→ 23 -= 1All 4 passes — pass 1 is the card above pass birthdate.monthcurrent_date.yearcalendarbirthdate.daymonthsyearsprev_monthprev_yeardays_in_prevdays1 11 2025 <module 'calendar' from '/usr/local/lib/python3.12/calendar.py'> 30 2 24 → 23 12 2024 31 30 2 3 — — 15 10 34 → 33 — — — 14 3 7 — — 22 6 39 → 38 — — — 7 4 11 2025 <module 'calendar' from '/usr/local/lib/python3.12/calendar.py'> 30 2 24 → 23 12 2024 31 30 months ← 1, prev_month ← 12, prev_year ← 2024, days_in_prev ← 31
pass 1 of 243if current_date.day >= birthdate.day:44 days = current_date.day - birthdate.day45else:46 months→ 1 -= 147 if months < 0:48 months = 1149 years -= 150 # Days in previous month51 import calendar52 prev_month→ 12 = current_date.month1 - 1 if current_date.month > 1 else 1253 prev_year→ 2024 = current_date.year2025 if current_date.month1 > 1 else current_date.year - 154 days_in_prev→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(prev_year2024, prev_month12)[1]55 days→ 30 = days_in_prev31 - birthdate.day30 + current_date.day29return years, months, days
57return years23, months1, days30years ← 23, months ← 1, days ← 30, total_days ← 8826
59years→ 23, months→ 1, days→ 30 = age_breakdown(birthday2000-11-30, today2025-01-29)60print(f"Age breakdown: {years23} years, {months1} months, {days30} days")6162# Age in different units63print("\nAge in different units:")64total_days→ 8826 = (today - birthday).days882665print("Days:", total_days8826)66print("Weeks:", total_days8826 // 7)67print("Months (approx):", total_days8826 // 30)68print("Years (approx):", total_days8826 // 365)6970# Next birthday71def next_birthday(birthdate, current_date):72 """Calculate next birthday"""73 next_bd = date(current_date.year, birthdate.month, birthdate.day)74 if next_bd <= current_date:75 next_bd = date(current_date.year + 1, birthdate.month, birthdate.day)76 return next_bd7778next_bd = next_birthday(birthday2000-11-30, today2025-01-29)79days_until = (next_bd - today).daysoutputAge breakdown: 23 years, 1 months, 30 days Age in different units: Days: 8826 Weeks: 1260 Months (approx): 294 Years (approx): 24next_bd ← 2025-11-30
70# Next birthday71def next_birthday(birthdate2000-11-30, current_date2025-01-29):72 """Calculate next birthday"""73 next_bd→ 2025-11-30 = date(current_date.year2025, birthdate.month11, birthdate.day30)74 if next_bd <= current_date:75 next_bd = date(current_date.year + 1, birthdate.month, birthdate.day)76 return next_bd2025-11-30next_bd ← 2025-11-30, days_until ← 305, check_dates ← [datetime.date(2020, 1, 1), datetime.date(2025, 1, 1), datetime.date(2030, 12, 31)]
78next_bd→ 2025-11-30 = next_birthday(birthday2000-11-30, today2025-01-29)79days_until→ 305 = (next_bd - today).days30580print("\nNext birthday:", next_bd2025-11-30)81print("Days until birthday:", days_until305)8283# Age at specific dates84print("\nAge at specific dates:")85check_dates→ [datetime.date(2020, 1, 1), datetime.date(2025, 1, 1), datetime.date(2030, 12, 31)] = [86 date(2020, 1, 1),87 date(2025, 1, 1),88 date(2030, 12, 31)89]output Next birthday: 2025-11-30 Days until birthday: 305 Age at specific dates:for check_date in check_dates:
pass 1 of 391for check_date2020-01-01 in check_dates[datetime.date(2020, 1, 1), datetime.date(2025, 1, 1), datetime.date(2030, 12, 31)]:92 age_at = calculate_age(birthday2000-11-30, check_date2020-01-01)93 print(f"Age on {check_date}: {age_at}")All 3 passes — pass 1 is the card above pass check_date1 2020-01-01 2 2025-01-01 3 2030-12-31 return age
25 age -= 126return age19age_at ← 19
91for check_date in check_dates:92 age_at→ 19 = calculate_age(birthday2000-11-30, check_date2020-01-01)93 print(f"Age on {check_date2020-01-01}: {age_at19}")outputAge on 2020-01-01: 19return age
25 age -= 126return age24age_at ← 24
91for check_date in check_dates:92 age_at→ 24 = calculate_age(birthday2000-11-30, check_date2025-01-01)93 print(f"Age on {check_date2025-01-01}: {age_at24}")outputAge on 2025-01-01: 24age_at ← 30
91for check_date in check_dates:92 age_at→ 30 = calculate_age(birthday2000-11-30, check_date2030-12-31)93 print(f"Age on {check_date2030-12-31}: {age_at30}")outputAge on 2030-12-31: 30people ← [(datetime.date(1990, 3, 15), 'Person 1'), (datetime.date(1985, 7, 22), 'Person 2'), (datetime.date(2000, 11, 30), 'Person 3')]
95# Multiple people96print("\nMultiple people:")97people→ [(datetime.date(1990, 3, 15), 'Person 1'), (datetime.date(1985, 7, 22), 'Person 2'), (datetime.date(2000, 11, 30), 'Person 3')] = [98 (date(1990, 3, 15), "Person 1"),99 (date(1985, 7, 22), "Person 2"),100 (date(2000, 11, 30), "Person 3")101]output Multiple people:for birth, name in people:
pass 1 of 3103for birth1990-03-15, namePerson 1 in people[(datetime.date(1990, 3, 15), 'Person 1'), (datetime.date(1985, 7, 22), 'Person 2'), (datetime.date(2000, 11, 30), 'Person 3')]:104 years, months, days = age_breakdown(birth1990-03-15, today2025-01-29)105 print(f"{name} (born {birth}): {years}y {months}m {days}d")All 3 passes — pass 1 is the card above pass birthname1 1990-03-15 Person 1 2 1985-07-22 Person 2 3 2000-11-30 Person 3 return age
25 age -= 126return age34years ← 34
33"""Calculate age in years, months, and days"""34years→ 34 = calculate_age(birthdate1990-03-15, current_date2025-01-29)days ← 14
pass 1 of 243if current_date.day29 >= birthdate.day15:44 days→ 14 = current_date.day29 - birthdate.day1545else:return years, months, days
57return years33, months10, days14years ← 33, months ← 10, days ← 14
103for birth, name in people:104 years→ 33, months→ 10, days→ 14 = age_breakdown(birth1990-03-15, today2025-01-29)105 print(f"{namePerson 1} (born {birth1990-03-15}): {years33}y {months10}m {days14}d")outputPerson 1 (born 1990-03-15): 33y 10m 14dreturn age
25 age -= 126return age39years ← 39
33"""Calculate age in years, months, and days"""34years→ 39 = calculate_age(birthdate1985-07-22, current_date2025-01-29)days ← 7
pass 2 of 243if current_date.day29 >= birthdate.day22:44 days→ 7 = current_date.day29 - birthdate.day2245else:return years, months, days
57return years38, months6, days7years ← 38, months ← 6, days ← 7
103for birth, name in people:104 years→ 38, months→ 6, days→ 7 = age_breakdown(birth1985-07-22, today2025-01-29)105 print(f"{namePerson 2} (born {birth1985-07-22}): {years38}y {months6}m {days7}d")outputPerson 2 (born 1985-07-22): 38y 6m 7dreturn age
25 age -= 126return age24years ← 24
33"""Calculate age in years, months, and days"""34years→ 24 = calculate_age(birthdate2000-11-30, current_date2025-01-29)months ← 1, prev_month ← 12, prev_year ← 2024, days_in_prev ← 31
pass 2 of 243if current_date.day >= birthdate.day:44 days = current_date.day - birthdate.day45else:46 months→ 1 -= 147 if months < 0:48 months = 1149 years -= 150 # Days in previous month51 import calendar52 prev_month→ 12 = current_date.month1 - 1 if current_date.month > 1 else 1253 prev_year→ 2024 = current_date.year2025 if current_date.month1 > 1 else current_date.year - 154 days_in_prev→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(prev_year2024, prev_month12)[1]55 days→ 30 = days_in_prev31 - birthdate.day30 + current_date.day29return years, months, days
57return years23, months1, days30years ← 23, months ← 1, days ← 30
103for birth, name in people:104 years→ 23, months→ 1, days→ 30 = age_breakdown(birth2000-11-30, today2025-01-29)105 print(f"{namePerson 3} (born {birth2000-11-30}): {years23}y {months1}m {days30}d")outputPerson 3 (born 2000-11-30): 23y 1m 30dprint("Is 18 or older?", is_minimum_age(birthday, today, 18))
112print("\nAge verification:")113print("Is 18 or older?", is_minimum_age(birthday2000-11-30, today2025-01-29, 18))114print("Is 21 or older?", is_minimum_age(birthday, today, 21))output Age verification:def is_minimum_age(birthdate, current_date, min_age):
pass 1 of 3107# Age verification108def is_minimum_age(birthdate2000-11-30, current_date2025-01-29, min_age18):109 """Check if person meets minimum age"""110 return calculate_age(birthdate2000-11-30, current_date2025-01-29) >= min_age18All 3 passes — pass 1 is the card above pass min_age1 18 2 21 3 65 return age
25 age -= 126return age24print("Is 18 or older?", is_minimum_age(birthday, today, 18))
112print("\nAge verification:")113print("Is 18 or older?", is_minimum_age(birthday2000-11-30, today2025-01-29, 18))114print("Is 21 or older?", is_minimum_age(birthday2000-11-30, today2025-01-29, 21))115print("Is 65 or older?", is_minimum_age(birthday, today, 65))outputIs 18 or older? Truereturn age
25 age -= 126return age24print("Is 21 or older?", is_minimum_age(birthday, today, 21))
113print("Is 18 or older?", is_minimum_age(birthday, today, 18))114print("Is 21 or older?", is_minimum_age(birthday2000-11-30, today2025-01-29, 21))115print("Is 65 or older?", is_minimum_age(birthday2000-11-30, today2025-01-29, 65))outputIs 21 or older? Truereturn age
25 age -= 126return age24print("Is 65 or older?", is_minimum_age(birthday, today, 65))
114print("Is 21 or older?", is_minimum_age(birthday, today, 21))115print("Is 65 or older?", is_minimum_age(birthday2000-11-30, today2025-01-29, 65))116117# Age groups118def get_age_group(birthdate, current_date):119 """Get age group category"""120 age = calculate_age(birthdate, current_date)121 if age < 13:122 return "Child"123 elif age < 18:124 return "Teenager"125 elif age < 65:126 return "Adult"127 else:128 return "Senior"129130print("\nAge group:", get_age_group(birthday2000-11-30, today2025-01-29))outputIs 65 or older? Falsedef get_age_group(birthdate, current_date):
117# Age groups118def get_age_group(birthdate2000-11-30, current_date2025-01-29):119 """Get age group category"""120 age = calculate_age(birthdate2000-11-30, current_date2025-01-29)121 if age < 13:return age
25 age -= 126return age24age ← 24
119"""Get age group category"""120age→ 24 = calculate_age(birthdate2000-11-30, current_date2025-01-29)121if age < 13:elif age < 65:
124 return "Teenager"125elif age24 < 65:126 return "Adult"127else:milestones ← [18, 21, 30, 40, 50, 65]
130print("\nAge group:", get_age_group(birthday2000-11-30, today2025-01-29))131132# Milestone birthdays133print("\nMilestone birthdays:")134milestones→ [18, 21, 30, 40, 50, 65] = [18, 21, 30, 40, 50, 65]135current_age = calculate_age(birthday2000-11-30, today2025-01-29)output Age group: Adult Milestone birthdays:return age
25 age -= 126return age24current_age ← 24
134milestones = [18, 21, 30, 40, 50, 65]135current_age→ 24 = calculate_age(birthday2000-11-30, today2025-01-29)for milestone in milestones:
pass 1 of 6137for milestone18 in milestones[18, 21, 30, 40, 50, 65]:138 if milestone > current_age:139 milestone_date = date(birthday.year + milestone, birthday.month, birthday.day)All 6 passes — pass 1 is the card above pass milestone1 18 2 21 3 30 4 40 5 50 6 65 milestone_date ← 2030-11-30, days_until_milestone ← 2131
pass 1 of 4137for milestone in milestones:138 if milestone30 > current_age24:139 milestone_date→ 2030-11-30 = date(birthday.year2000 + milestone30, birthday.month11, birthday.day30)140 days_until_milestone→ 2131 = (milestone_date - today).days2131141 print(f"{milestone30} years: {milestone_date2030-11-30} (in {days_until_milestone2131} days)")output30 years: 2030-11-30 (in 2131 days)All 4 passes — pass 1 is the card above pass milestone(milestone_date - today).daysmilestone_datedays_until_milestone1 30 2131 2030-11-30 2131 2 40 5784 2040-11-30 5784 3 50 9436 2050-11-30 9436 4 65 14915 2065-11-30 14915 retirement_age ← 65, retirement_date ← 2065-11-30
143# Retirement144print("\nRetirement:")145retirement_age→ 65 = 65146retirement_date→ 2065-11-30 = date(birthday.year2000 + retirement_age65, birthday.month11, birthday.day30)147years_to_retirement = calculate_age(today2025-01-29, retirement_date2065-11-30)148days_to_retirement = (retirement_date - today).daysoutput Retirement:years_to_retirement ← 40, days_to_retirement ← 14915
146retirement_date = date(birthday.year + retirement_age, birthday.month, birthday.day)147years_to_retirement→ 40 = calculate_age(today2025-01-29, retirement_date2065-11-30)148days_to_retirement→ 14915 = (retirement_date - today).days14915149150print("Retirement date:", retirement_date2065-11-30)151if retirement_date > today:outputRetirement date: 2065-11-30if retirement_date > today:
150print("Retirement date:", retirement_date)151if retirement_date2065-11-30 > today2025-01-29:152 print("Years to retirement:", years_to_retirement40)153 print("Days to retirement:", days_to_retirement14915)154else:outputYears to retirement: 40 Days to retirement: 14915
age_calc
Calculating age in years, months, or days from a birth date
Working with Months
month.py
Replay: real traced execution (multi-file project)
# Month operations
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta
import calendar
# Month operations
d = date(2025, 1, 29)
print("Date:", d)
print()
# Get month
print("Month:", d.month)
print("Month name:", calendar.month_name[d.month])
print("Short name:", calendar.month_abbr[d.month])
# All month names
print("\nAll months:")
for i in range(1, 13):
print(f"{i:2}: {calendar.month_name[i]}")
# Month info
print("\nMonth info:")
year, month = 2025, 1
first_weekday, days_in_month = calendar.monthrange(year, month)
print(f"First day weekday: {first_weekday} ({calendar.day_name[first_weekday]})")
print(f"Days in month: {days_in_month}")
# First/last day of month
def first_day_of_month(d):
"""Get first day of month"""
return date(d.year, d.month, 1)
def last_day_of_month(d):
"""Get last day of month"""
_, days = calendar.monthrange(d.year, d.month)
return date(d.year, d.month, days)
print("\nFirst/last day:")
print("First day:", first_day_of_month(d))
print("Last day:", last_day_of_month(d))
# Month lengths
print("\nMonth lengths (2025):")
for month in range(1, 13):
_, days = calendar.monthrange(2025, month)
print(f"{calendar.month_name[month]:10}: {days} days")
# Leap year
print("\nLeap year:")
print("2024:", calendar.isleap(2024))
print("2025:", calendar.isleap(2025))
print("February 2024:", calendar.monthrange(2024, 2)[1], "days")
print("February 2025:", calendar.monthrange(2025, 2)[1], "days")
# Add months (using relativedelta)
print("\nAdd months (with relativedelta):")
try:
# relativedelta handles month arithmetic properly
next_month = d + relativedelta(months=1)
print("+1 month:", next_month)
prev_month = d - relativedelta(months=1)
print("-1 month:", prev_month)
three_months = d + relativedelta(months=3)
print("+3 months:", three_months)
except NameError:
print("(Install python-dateutil for relativedelta)")
# Manual approximation
print("+1 month (approx):", d + timedelta(days=30))
# Month arithmetic (manual)
print("\nMonth arithmetic (manual):")
def add_months_manual(d, months):
"""Add months to date (simple implementation)"""
month = d.month - 1 + months
year = d.year + month // 12
month = month % 12 + 1
day = min(d.day, calendar.monthrange(year, month)[1])
return date(year, month, day)
print("Jan 31 + 1 month:", add_months_manual(date(2025, 1, 31), 1))
print("Jan 31 + 2 months:", add_months_manual(date(2025, 1, 31), 2))
# Quarter dates
print("\nQuarterly dates:")
q1_end = date(2025, 3, 31)
q2_end = add_months_manual(q1_end, 3)
q3_end = add_months_manual(q2_end, 3)
q4_end = add_months_manual(q3_end, 3)
print("Q1 end:", q1_end)
print("Q2 end:", q2_end)
print("Q3 end:", q3_end)
print("Q4 end:", q4_end)
# Monthly billing
print("\nMonthly billing dates:")
billing_day = 15
for month in range(1, 7):
bill_date = date(2025, month, billing_day)
print(f"Month {month}: {bill_date}")
# End of each month
print("\nEnd of each month (2025):")
for month in range(1, 13):
_, days = calendar.monthrange(2025, month)
month_end = date(2025, month, days)
print(f"{calendar.month_name[month]:10}: {month_end}")
# Month range iteration
print("\nMonth range:")
start = date(2025, 1, 15)
end = date(2025, 4, 20)
current = date(start.year, start.month, 1)
while current <= end:
_, days = calendar.monthrange(current.year, current.month)
print(f"{current.year}-{current.month:02}: {days} days")
current = add_months_manual(current, 1)
# Calendar display
print("\nCalendar for January 2025:")
print(calendar.month(2025, 1))
d ← 2025-01-29
7# Month operations8d→ 2025-01-29 = date(2025, 1, 29)9print("Date:", d2025-01-29)10print()1112# Get month13print("Month:", d.month1)14print("Month name:", calendar.month_name[d.month]January)15print("Short name:", calendar.month_abbr[d.month]Jan)1617# All month names18print("\nAll months:")19for i in range(1, 13):outputDate: 2025-01-29 Month: 1 Month name: January Short name: Jan All months:for i in range(1, 13):
pass 1 of 1218print("\nAll months:")19for i1 in range(1, 13):20 print(f"{i1:2}: {calendar.month_name[i]January}")output 1: JanuaryAll 12 passes — pass 1 is the card above pass icalendar.month_name[i]1 1 January 2 2 February 3 3 March 4 4 April 5 5 May 6 6 June 7 7 July 8 8 August 9 9 September 10 10 October 11 11 November 12 12 December year ← 2025, month ← 1, first_weekday ← 2, days_in_month ← 31
22# Month info23print("\nMonth info:")24year→ 2025, month→ 1 = 2025, 125first_weekday→ 2, days_in_month→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(year2025, month1)26print(f"First day weekday: {first_weekday2} ({calendar.day_name[first_weekday]Wednesday})")27print(f"Days in month: {days_in_month31}")2829# First/last day of month30def first_day_of_month(d):31 """Get first day of month"""32 return date(d.year, d.month, 1)3334def last_day_of_month(d):35 """Get last day of month"""36 _, days = calendar.monthrange(d.year, d.month)37 return date(d.year, d.month, days)3839print("\nFirst/last day:")40print("First day:", first_day_of_month(d2025-01-29))41print("Last day:", last_day_of_month(d))output Month info: First day weekday: 2 (Wednesday) Days in month: 31 First/last day:def first_day_of_month(d):
29# First/last day of month30def first_day_of_month(d2025-01-29):31 """Get first day of month"""32 return date(d.year2025, d.month1, 1)print("First day:", first_day_of_month(d))
39print("\nFirst/last day:")40print("First day:", first_day_of_month(d2025-01-29))41print("Last day:", last_day_of_month(d2025-01-29))outputFirst day: 2025-01-01_ ← 2, days ← 31
34def last_day_of_month(d2025-01-29):35 """Get last day of month"""36 _→ 2, days→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(d.year2025, d.month1)37 return date(d.year2025, d.month1, days31)print("Last day:", last_day_of_month(d))
40print("First day:", first_day_of_month(d))41print("Last day:", last_day_of_month(d2025-01-29))4243# Month lengths44print("\nMonth lengths (2025):")45for month in range(1, 13):outputLast day: 2025-01-31 Month lengths (2025):_ ← 2, days ← 31
pass 1 of 1244print("\nMonth lengths (2025):")45for month1 in range(1, 13):46 _→ 2, days→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(2025, month1)47 print(f"{calendar.month_name[month]January:10}: {days31} days")outputJanuary : 31 daysAll 12 passes — pass 1 is the card above pass monthcalendar.month_name[month]_days1 1 January 2 31 2 2 February 5 28 3 3 March 5 31 4 4 April 1 30 5 5 May 3 31 6 6 June 6 30 7 7 July 1 31 8 8 August 4 31 9 9 September 0 30 10 10 October 2 31 11 11 November 5 30 12 12 December 0 31 print("2024:", calendar.isleap(2024))
49# Leap year50print("\nLeap year:")51print("2024:", calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.isleap(2024))52print("2025:", calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.isleap(2025))53print("February 2024:", calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(2024, 2)[1], "days")54print("February 2025:", calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(2025, 2)[1], "days")5556# Add months (using relativedelta)57print("\nAdd months (with relativedelta):")58try:output Leap year: 2024: True 2025: False February 2024: 29 days February 2025: 28 days Add months (with relativedelta):next_month ← 2025-02-28, prev_month ← 2024-12-29, three_months ← 2025-04-29
57print("\nAdd months (with relativedelta):")58try:59 # relativedelta handles month arithmetic properly60 next_month→ 2025-02-28 = d2025-01-29 + relativedelta(months=1)61 print("+1 month:", next_month2025-02-28)62 63 prev_month→ 2024-12-29 = d2025-01-29 - relativedelta(months=1)64 print("-1 month:", prev_month2024-12-29)65 66 three_months→ 2025-04-29 = d2025-01-29 + relativedelta(months=3)67 print("+3 months:", three_months2025-04-29)68except NameError:output+1 month: 2025-02-28 -1 month: 2024-12-29 +3 months: 2025-04-29print(" Month arithmetic (manual):")
73# Month arithmetic (manual)74print("\nMonth arithmetic (manual):")75def add_months_manual(d, months):76 """Add months to date (simple implementation)"""77 month = d.month - 1 + months78 year = d.year + month // 1279 month = month % 12 + 180 day = min(d.day, calendar.monthrange(year, month)[1])81 return date(year, month, day)8283print("Jan 31 + 1 month:", add_months_manual(date(2025, 1, 31), 1))84print("Jan 31 + 2 months:", add_months_manual(date(2025, 1, 31), 2))output Month arithmetic (manual):month ← 1, year ← 2025, day ← 28
pass 1 of 974print("\nMonth arithmetic (manual):")75def add_months_manual(d2025-01-31, months1):76 """Add months to date (simple implementation)"""77 month→ 1 = d.month1 - 1 + months178 year→ 2025 = d.year2025 + month1 // 1279 month→ 2 = month % 12 + 180 day→ 28 = min(d.day31, calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(year2025, month2)[1])81 return date(year2025, month2, day28)All 9 passes — pass 1 is the card above pass dmonthsd.monthd.daymonthyearday1 2025-01-31 1 1 31 1 2025 28 2 2025-01-31 2 1 31 2 2025 31 3 2025-03-31 3 3 31 5 2025 30 4 2025-06-30 3 6 30 8 2025 30 5 2025-09-30 3 9 30 11 2025 30 6 2025-01-01 1 1 1 1 2025 1 7 2025-02-01 1 2 1 2 2025 1 8 2025-03-01 1 3 1 3 2025 1 9 2025-04-01 1 4 1 4 2025 1 print("Jan 31 + 1 month:", add_months_manual(date(2025, 1, 31), 1))
83print("Jan 31 + 1 month:", add_months_manual(date(2025, 1, 31), 1))84print("Jan 31 + 2 months:", add_months_manual(date(2025, 1, 31), 2))outputJan 31 + 1 month: 2025-02-28q1_end ← 2025-03-31
83print("Jan 31 + 1 month:", add_months_manual(date(2025, 1, 31), 1))84print("Jan 31 + 2 months:", add_months_manual(date(2025, 1, 31), 2))8586# Quarter dates87print("\nQuarterly dates:")88q1_end→ 2025-03-31 = date(2025, 3, 31)89q2_end = add_months_manual(q1_end2025-03-31, 3)90q3_end = add_months_manual(q2_end, 3)outputJan 31 + 2 months: 2025-03-31 Quarterly dates:q2_end ← 2025-06-30
88q1_end = date(2025, 3, 31)89q2_end→ 2025-06-30 = add_months_manual(q1_end2025-03-31, 3)90q3_end = add_months_manual(q2_end2025-06-30, 3)91q4_end = add_months_manual(q3_end, 3)q3_end ← 2025-09-30
89q2_end = add_months_manual(q1_end, 3)90q3_end→ 2025-09-30 = add_months_manual(q2_end2025-06-30, 3)91q4_end = add_months_manual(q3_end2025-09-30, 3)q4_end ← 2025-12-30, billing_day ← 15
90q3_end = add_months_manual(q2_end, 3)91q4_end→ 2025-12-30 = add_months_manual(q3_end2025-09-30, 3)9293print("Q1 end:", q1_end2025-03-31)94print("Q2 end:", q2_end2025-06-30)95print("Q3 end:", q3_end2025-09-30)96print("Q4 end:", q4_end2025-12-30)9798# Monthly billing99print("\nMonthly billing dates:")100billing_day→ 15 = 15101for month in range(1, 7):outputQ1 end: 2025-03-31 Q2 end: 2025-06-30 Q3 end: 2025-09-30 Q4 end: 2025-12-30 Monthly billing dates:bill_date ← 2025-01-15
pass 1 of 6100billing_day = 15101for month1 in range(1, 7):102 bill_date→ 2025-01-15 = date(2025, month1, billing_day15)103 print(f"Month {month1}: {bill_date2025-01-15}")outputMonth 1: 2025-01-15All 6 passes — pass 1 is the card above pass monthbill_date1 1 2025-01-15 2 2 2025-02-15 3 3 2025-03-15 4 4 2025-04-15 5 5 2025-05-15 6 6 2025-06-15 print(" End of each month (2025):")
105# End of each month106print("\nEnd of each month (2025):")107for month in range(1, 13):output End of each month (2025):_ ← 2, days ← 31, month_end ← 2025-01-31
pass 1 of 12106print("\nEnd of each month (2025):")107for month1 in range(1, 13):108 _→ 2, days→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(2025, month1)109 month_end→ 2025-01-31 = date(2025, month1, days31)110 print(f"{calendar.month_name[month]January:10}: {month_end2025-01-31}")outputJanuary : 2025-01-31All 12 passes — pass 1 is the card above pass monthcalendar.month_name[month]_daysmonth_end1 1 January 2 31 2025-01-31 2 2 February 5 28 2025-02-28 3 3 March 5 31 2025-03-31 4 4 April 1 30 2025-04-30 5 5 May 3 31 2025-05-31 6 6 June 6 30 2025-06-30 7 7 July 1 31 2025-07-31 8 8 August 4 31 2025-08-31 9 9 September 0 30 2025-09-30 10 10 October 2 31 2025-10-31 11 11 November 5 30 2025-11-30 12 12 December 0 31 2025-12-31 start ← 2025-01-15, end ← 2025-04-20, current ← 2025-01-01
112# Month range iteration113print("\nMonth range:")114start→ 2025-01-15 = date(2025, 1, 15)115end→ 2025-04-20 = date(2025, 4, 20)116117current→ 2025-01-01 = date(start.year2025, start.month1, 1)118while current <= end:output Month range:_ ← 2, days ← 31
pass 1 of 4117current = date(start.year, start.month, 1)118while current2025-01-01 <= end2025-04-20:119 _→ 2, days→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(current.year2025, current.month1)120 print(f"{current.year2025}-{current.month1:02}: {days31} days")121 current = add_months_manual(current2025-01-01, 1)output2025-01: 31 daysAll 4 passes — pass 1 is the card above pass currentcurrent.month_days1 2025-01-01 1 2 31 2 2025-02-01 2 5 28 3 2025-03-01 3 5 31 4 2025-04-01 4 1 30 current ← 2025-02-01
120print(f"{current.year}-{current.month:02}: {days} days")121current→ 2025-02-01 = add_months_manual(current, 1)current ← 2025-03-01
120print(f"{current.year}-{current.month:02}: {days} days")121current→ 2025-03-01 = add_months_manual(current, 1)current ← 2025-04-01
120print(f"{current.year}-{current.month:02}: {days} days")121current→ 2025-04-01 = add_months_manual(current, 1)current ← 2025-05-01
120print(f"{current.year}-{current.month:02}: {days} days")121current→ 2025-05-01 = add_months_manual(current, 1)print(calendar.month(2025, 1))
123# Calendar display124print("\nCalendar for January 2025:")125print(calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.month(2025, 1))output Calendar for January 2025: January 2025 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
month_operations
Finding first/last day of month and month arithmetic
timedelta
Represents a duration:
timedelta(days=7)timedelta(hours=2, minutes=30)- Supports addition/subtraction
Calendar Module
The calendar module provides additional date utilities for month ranges and leap year checking.
Exercise: practical.py
Build a deadline calculator with working days, trial periods, and billing cycles