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.
Working with Months
arithmetic.py
# Add and subtract dates
from datetime import date, datetime, timedelta
# Date arithmetic
today =
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 =
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 =
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))
difference.py
# 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)))
dayofweek.py
# 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}")
age.py
# Age calculation
from datetime import date, timedelta
# Age calculation
birthday =
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 =
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 =
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")
month.py
# 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))
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.
date_arithmetic
Adding and subtracting days, weeks, and other periods with timedelta
date_difference
Finding the duration between two dates or datetimes
day_of_week
Finding weekday, checking for weekends, and calendar operations
age_calc
Calculating age in years, months, or days from a birth date
month_operations
Finding first/last day of month and month arithmetic
Exercise: practical.py
Build a deadline calculator with working days, trial periods, and billing cycles