Applications frequently work with dates for birthdays, deadlines, and scheduling. Python's date class from the datetime module represents calendar dates without time components. Understanding date creation, component access, and basic operations forms the foundation for all date-based programming.

date from the datetime module represents a date without time (year, month, day).

Creating Dates

date1
create.py
Replay: real traced execution (multi-file project)
# Create specific date

from datetime import date
import calendar

# Create specific dates
# Create with year, month, day
date1 = date(2025, 1, 29)
print(f"Date 1: {date1}")

# Special dates
new_year = date(2025, 1, 1)
print(f"\nNew Year 2025: {new_year}")

christmas = date(2025, 12, 25)
print(f"Christmas 2025: {christmas}")

# First day of month
today = date.today().replace(year=2025, month=1, day=15)
first_of_month = date(today.year, today.month, 1)
print(f"\nFirst of this month: {first_of_month}")

# Last day of month
_, last_day = calendar.monthrange(today.year, today.month)
last_of_month = date(today.year, today.month, last_day)
print(f"Last of this month: {last_of_month}")

# First day of year
first_of_year = date(today.year, 1, 1)
print(f"First of this year: {first_of_year}")

# Replace components
modified = date1.replace(year=2026, month=6, day=15)
print(f"\nModified date: {modified}")

# Only change year
next_year = date1.replace(year=date1.year + 1)
print(f"Next year same date: {next_year}")

# Min and max dates
min_date = date.min
max_date = date.max
print(f"\nMin date: {min_date}")
print(f"Max date: {max_date}")

# From ordinal (days since year 1)
ordinal = 738000
from_ordinal = date.fromordinal(ordinal)
print(f"\nFrom ordinal {ordinal}: {from_ordinal}")

# To ordinal
to_ordinal = date1.toordinal()
print(f"{date1} to ordinal: {to_ordinal}")

# From timestamp
timestamp = 1736937000.0
from_timestamp = date.fromtimestamp(timestamp)
print(f"\nFrom timestamp: {from_timestamp}")

# Create dates for a week
print("\nWeek dates:")
monday = date(2025, 1, 27)
for i in range(7):
    from datetime import timedelta
    day = monday + timedelta(days=i)
    print(f"  {day} ({calendar.day_name[day.weekday()]})")

# Create specific date

from datetime import date
import calendar

# Create specific dates
# Create with year, month, day
date1 = date(2024, 3, 1)
print(f"Date 1: {date1}")

# Special dates
new_year = date(2025, 1, 1)
print(f"\nNew Year 2025: {new_year}")

christmas = date(2025, 12, 25)
print(f"Christmas 2025: {christmas}")

# First day of month
today = date.today().replace(year=2025, month=1, day=15)
first_of_month = date(today.year, today.month, 1)
print(f"\nFirst of this month: {first_of_month}")

# Last day of month
_, last_day = calendar.monthrange(today.year, today.month)
last_of_month = date(today.year, today.month, last_day)
print(f"Last of this month: {last_of_month}")

# First day of year
first_of_year = date(today.year, 1, 1)
print(f"First of this year: {first_of_year}")

# Replace components
modified = date1.replace(year=2026, month=6, day=15)
print(f"\nModified date: {modified}")

# Only change year
next_year = date1.replace(year=date1.year + 1)
print(f"Next year same date: {next_year}")

# Min and max dates
min_date = date.min
max_date = date.max
print(f"\nMin date: {min_date}")
print(f"Max date: {max_date}")

# From ordinal (days since year 1)
ordinal = 738000
from_ordinal = date.fromordinal(ordinal)
print(f"\nFrom ordinal {ordinal}: {from_ordinal}")

# To ordinal
to_ordinal = date1.toordinal()
print(f"{date1} to ordinal: {to_ordinal}")

# From timestamp
timestamp = 1736937000.0
from_timestamp = date.fromtimestamp(timestamp)
print(f"\nFrom timestamp: {from_timestamp}")

# Create dates for a week
print("\nWeek dates:")
monday = date(2025, 1, 27)
for i in range(7):
    from datetime import timedelta
    day = monday + timedelta(days=i)
    print(f"  {day} ({calendar.day_name[day.weekday()]})")

# Create specific date

from datetime import date
import calendar

# Create specific dates
# Create with year, month, day
date1 = date(2026, 6, 15)
print(f"Date 1: {date1}")

# Special dates
new_year = date(2025, 1, 1)
print(f"\nNew Year 2025: {new_year}")

christmas = date(2025, 12, 25)
print(f"Christmas 2025: {christmas}")

# First day of month
today = date.today().replace(year=2025, month=1, day=15)
first_of_month = date(today.year, today.month, 1)
print(f"\nFirst of this month: {first_of_month}")

# Last day of month
_, last_day = calendar.monthrange(today.year, today.month)
last_of_month = date(today.year, today.month, last_day)
print(f"Last of this month: {last_of_month}")

# First day of year
first_of_year = date(today.year, 1, 1)
print(f"First of this year: {first_of_year}")

# Replace components
modified = date1.replace(year=2026, month=6, day=15)
print(f"\nModified date: {modified}")

# Only change year
next_year = date1.replace(year=date1.year + 1)
print(f"Next year same date: {next_year}")

# Min and max dates
min_date = date.min
max_date = date.max
print(f"\nMin date: {min_date}")
print(f"Max date: {max_date}")

# From ordinal (days since year 1)
ordinal = 738000
from_ordinal = date.fromordinal(ordinal)
print(f"\nFrom ordinal {ordinal}: {from_ordinal}")

# To ordinal
to_ordinal = date1.toordinal()
print(f"{date1} to ordinal: {to_ordinal}")

# From timestamp
timestamp = 1736937000.0
from_timestamp = date.fromtimestamp(timestamp)
print(f"\nFrom timestamp: {from_timestamp}")

# Create dates for a week
print("\nWeek dates:")
monday = date(2025, 1, 27)
for i in range(7):
    from datetime import timedelta
    day = monday + timedelta(days=i)
    print(f"  {day} ({calendar.day_name[day.weekday()]})")

  1. date1 ← 2025-01-29, new_year ← 2025-01-01, christmas ← 2025-12-25

    7# Create with year, month, day8date1→ 2025-01-29 = date(2025, 1, 29)  #@date1=date(2024, 3, 1), date(2026, 6, 15)9print(f"Date 1: {date12025-01-29}")1011# Special dates12new_year→ 2025-01-01 = date(2025, 1, 1)13print(f"\nNew Year 2025: {new_year2025-01-01}")1415christmas→ 2025-12-25 = date(2025, 12, 25)16print(f"Christmas 2025: {christmas2025-12-25}")1718# First day of month19today→ 2025-01-15 = date<class 'datetime.date'>.today().replace(year=2025, month=1, day=15)20first_of_month→ 2025-01-01 = date(today.year2025, today.month1, 1)21print(f"\nFirst of this month: {first_of_month2025-01-01}")2223# Last day of month24_→ 2, last_day→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(today.year2025, today.month1)25last_of_month→ 2025-01-31 = date(today.year2025, today.month1, last_day31)26print(f"Last of this month: {last_of_month2025-01-31}")2728# First day of year29first_of_year→ 2025-01-01 = date(today.year2025, 1, 1)30print(f"First of this year: {first_of_year2025-01-01}")3132# Replace components33modified→ 2026-06-15 = date12025-01-29.replace(year=2026, month=6, day=15)34print(f"\nModified date: {modified2026-06-15}")3536# Only change year37next_year→ 2026-01-29 = date12025-01-29.replace(year=date1.year2025 + 1)38print(f"Next year same date: {next_year2026-01-29}")3940# Min and max dates41min_date→ 0001-01-01 = date.min0001-01-0142max_date→ 9999-12-31 = date.max9999-12-3143print(f"\nMin date: {min_date0001-01-01}")44print(f"Max date: {max_date9999-12-31}")4546# From ordinal (days since year 1)47ordinal→ 738000 = 73800048from_ordinal→ 2021-07-29 = date<class 'datetime.date'>.fromordinal(ordinal738000)49print(f"\nFrom ordinal {ordinal738000}: {from_ordinal2021-07-29}")5051# To ordinal52to_ordinal→ 739280 = date12025-01-29.toordinal()53print(f"{date12025-01-29} to ordinal: {to_ordinal739280}")5455# From timestamp56timestamp→ 1736937000.0 = 1736937000.057from_timestamp→ 2025-01-15 = date<class 'datetime.date'>.fromtimestamp(timestamp1736937000.0)58print(f"\nFrom timestamp: {from_timestamp2025-01-15}")5960# Create dates for a week61print("\nWeek dates:")62monday→ 2025-01-27 = date(2025, 1, 27)63for i in range(7):
    outputDate 1: 2025-01-29
    
    New Year 2025: 2025-01-01
    Christmas 2025: 2025-12-25
    
    First of this month: 2025-01-01
    Last of this month: 2025-01-31
    First of this year: 2025-01-01
    
    Modified date: 2026-06-15
    Next year same date: 2026-01-29
    
    Min date: 0001-01-01
    Max date: 9999-12-31
    
    From ordinal 738000: 2021-07-29
    2025-01-29 to ordinal: 739280
    
    From timestamp: 2025-01-15
    
    Week dates:
  2. day ← 2025-01-27

    pass 1 of 7
    62monday = date(2025, 1, 27)63for i0 in range(7):64    from datetime import timedelta65    day→ 2025-01-27 = monday2025-01-27 + timedelta(days=i0)66    print(f"  {day2025-01-27} ({calendar.day_name⟨_localized_day A⟩[day.weekday()]})")
    output  2025-01-27 (Monday)
    All 7 passes — pass 1 is the card above
    passiday
    102025-01-27
    212025-01-28
    322025-01-29
    432025-01-30
    542025-01-31
    652025-02-01
    762025-02-02
  1. date1 ← 2024-03-01, new_year ← 2025-01-01, christmas ← 2025-12-25

    7# Create with year, month, day8date1→ 2024-03-01 = date(2024, 3, 1)9print(f"Date 1: {date12024-03-01}")1011# Special dates12new_year→ 2025-01-01 = date(2025, 1, 1)13print(f"\nNew Year 2025: {new_year2025-01-01}")1415christmas→ 2025-12-25 = date(2025, 12, 25)16print(f"Christmas 2025: {christmas2025-12-25}")1718# First day of month19today→ 2025-01-15 = date<class 'datetime.date'>.today().replace(year=2025, month=1, day=15)20first_of_month→ 2025-01-01 = date(today.year2025, today.month1, 1)21print(f"\nFirst of this month: {first_of_month2025-01-01}")2223# Last day of month24_→ 2, last_day→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(today.year2025, today.month1)25last_of_month→ 2025-01-31 = date(today.year2025, today.month1, last_day31)26print(f"Last of this month: {last_of_month2025-01-31}")2728# First day of year29first_of_year→ 2025-01-01 = date(today.year2025, 1, 1)30print(f"First of this year: {first_of_year2025-01-01}")3132# Replace components33modified→ 2026-06-15 = date12024-03-01.replace(year=2026, month=6, day=15)34print(f"\nModified date: {modified2026-06-15}")3536# Only change year37next_year→ 2025-03-01 = date12024-03-01.replace(year=date1.year2024 + 1)38print(f"Next year same date: {next_year2025-03-01}")3940# Min and max dates41min_date→ 0001-01-01 = date.min0001-01-0142max_date→ 9999-12-31 = date.max9999-12-3143print(f"\nMin date: {min_date0001-01-01}")44print(f"Max date: {max_date9999-12-31}")4546# From ordinal (days since year 1)47ordinal→ 738000 = 73800048from_ordinal→ 2021-07-29 = date<class 'datetime.date'>.fromordinal(ordinal738000)49print(f"\nFrom ordinal {ordinal738000}: {from_ordinal2021-07-29}")5051# To ordinal52to_ordinal→ 738946 = date12024-03-01.toordinal()53print(f"{date12024-03-01} to ordinal: {to_ordinal738946}")5455# From timestamp56timestamp→ 1736937000.0 = 1736937000.057from_timestamp→ 2025-01-15 = date<class 'datetime.date'>.fromtimestamp(timestamp1736937000.0)58print(f"\nFrom timestamp: {from_timestamp2025-01-15}")5960# Create dates for a week61print("\nWeek dates:")62monday→ 2025-01-27 = date(2025, 1, 27)63for i in range(7):
    outputDate 1: 2024-03-01
    
    New Year 2025: 2025-01-01
    Christmas 2025: 2025-12-25
    
    First of this month: 2025-01-01
    Last of this month: 2025-01-31
    First of this year: 2025-01-01
    
    Modified date: 2026-06-15
    Next year same date: 2025-03-01
    
    Min date: 0001-01-01
    Max date: 9999-12-31
    
    From ordinal 738000: 2021-07-29
    2024-03-01 to ordinal: 738946
    
    From timestamp: 2025-01-15
    
    Week dates:
  2. day ← 2025-01-27

    pass 1 of 7
    62monday = date(2025, 1, 27)63for i0 in range(7):64    from datetime import timedelta65    day→ 2025-01-27 = monday2025-01-27 + timedelta(days=i0)66    print(f"  {day2025-01-27} ({calendar.day_name⟨_localized_day A⟩[day.weekday()]})")
    output  2025-01-27 (Monday)
    All 7 passes — pass 1 is the card above
    passiday
    102025-01-27
    212025-01-28
    322025-01-29
    432025-01-30
    542025-01-31
    652025-02-01
    762025-02-02
  1. date1 ← 2026-06-15, new_year ← 2025-01-01, christmas ← 2025-12-25

    7# Create with year, month, day8date1→ 2026-06-15 = date(2026, 6, 15)9print(f"Date 1: {date12026-06-15}")1011# Special dates12new_year→ 2025-01-01 = date(2025, 1, 1)13print(f"\nNew Year 2025: {new_year2025-01-01}")1415christmas→ 2025-12-25 = date(2025, 12, 25)16print(f"Christmas 2025: {christmas2025-12-25}")1718# First day of month19today→ 2025-01-15 = date<class 'datetime.date'>.today().replace(year=2025, month=1, day=15)20first_of_month→ 2025-01-01 = date(today.year2025, today.month1, 1)21print(f"\nFirst of this month: {first_of_month2025-01-01}")2223# Last day of month24_→ 2, last_day→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(today.year2025, today.month1)25last_of_month→ 2025-01-31 = date(today.year2025, today.month1, last_day31)26print(f"Last of this month: {last_of_month2025-01-31}")2728# First day of year29first_of_year→ 2025-01-01 = date(today.year2025, 1, 1)30print(f"First of this year: {first_of_year2025-01-01}")3132# Replace components33modified→ 2026-06-15 = date12026-06-15.replace(year=2026, month=6, day=15)34print(f"\nModified date: {modified2026-06-15}")3536# Only change year37next_year→ 2027-06-15 = date12026-06-15.replace(year=date1.year2026 + 1)38print(f"Next year same date: {next_year2027-06-15}")3940# Min and max dates41min_date→ 0001-01-01 = date.min0001-01-0142max_date→ 9999-12-31 = date.max9999-12-3143print(f"\nMin date: {min_date0001-01-01}")44print(f"Max date: {max_date9999-12-31}")4546# From ordinal (days since year 1)47ordinal→ 738000 = 73800048from_ordinal→ 2021-07-29 = date<class 'datetime.date'>.fromordinal(ordinal738000)49print(f"\nFrom ordinal {ordinal738000}: {from_ordinal2021-07-29}")5051# To ordinal52to_ordinal→ 739782 = date12026-06-15.toordinal()53print(f"{date12026-06-15} to ordinal: {to_ordinal739782}")5455# From timestamp56timestamp→ 1736937000.0 = 1736937000.057from_timestamp→ 2025-01-15 = date<class 'datetime.date'>.fromtimestamp(timestamp1736937000.0)58print(f"\nFrom timestamp: {from_timestamp2025-01-15}")5960# Create dates for a week61print("\nWeek dates:")62monday→ 2025-01-27 = date(2025, 1, 27)63for i in range(7):
    outputDate 1: 2026-06-15
    
    New Year 2025: 2025-01-01
    Christmas 2025: 2025-12-25
    
    First of this month: 2025-01-01
    Last of this month: 2025-01-31
    First of this year: 2025-01-01
    
    Modified date: 2026-06-15
    Next year same date: 2027-06-15
    
    Min date: 0001-01-01
    Max date: 9999-12-31
    
    From ordinal 738000: 2021-07-29
    2026-06-15 to ordinal: 739782
    
    From timestamp: 2025-01-15
    
    Week dates:
  2. day ← 2025-01-27

    pass 1 of 7
    62monday = date(2025, 1, 27)63for i0 in range(7):64    from datetime import timedelta65    day→ 2025-01-27 = monday2025-01-27 + timedelta(days=i0)66    print(f"  {day2025-01-27} ({calendar.day_name⟨_localized_day A⟩[day.weekday()]})")
    output  2025-01-27 (Monday)
    All 7 passes — pass 1 is the card above
    passiday
    102025-01-27
    212025-01-28
    322025-01-29
    432025-01-30
    542025-01-31
    652025-02-01
    762025-02-02
date_creation Creating date objects with date(), date.today(), and from timestamps

Getting Current Date

current.py
Replay: real traced execution (multi-file project)
# Current date

from datetime import date
import calendar

# Get current date
# Current date
today = date.today().replace(year=2025, month=1, day=15)
print(f"Today: {today}")

# Date components
year = today.year
month = today.month
day = today.day

print("\nDate components:")
print(f"Year: {year}")
print(f"Month: {month}")
print(f"Day: {day}")

# Day of week
# Monday is 0, Sunday is 6
weekday = today.weekday()
print(f"Day of week (0=Mon): {weekday}")

# ISO weekday (Monday is 1, Sunday is 7)
iso_weekday = today.isoweekday()
print(f"ISO day of week (1=Mon): {iso_weekday}")

# Day name
day_name = calendar.day_name[weekday]
print(f"Day name: {day_name}")

# Month name
month_name = calendar.month_name[month]
print(f"Month name: {month_name}")

# ISO calendar (year, week, weekday)
iso = today.isocalendar()
print(f"\nISO calendar:")
print(f"  Year: {iso[0]}")
print(f"  Week: {iso[1]}")
print(f"  Weekday: {iso[2]}")

# Alternative access
print(f"  Year: {iso.year}")
print(f"  Week: {iso.week}")
print(f"  Weekday: {iso.weekday}")

# Day of year
day_of_year = today.timetuple().tm_yday
print(f"\nDay of year: {day_of_year}")

# Is leap year
def is_leap_year(year):
    return calendar.isleap(year)

print(f"Is {year} a leap year: {is_leap_year(year)}")

# Days in month
days_in_month = calendar.monthrange(year, month)[1]
print(f"Days in {month_name}: {days_in_month}")

  1. today ← 2025-01-15, year ← 2025, month ← 1, day ← 15, weekday ← 2

    7# Current date8today→ 2025-01-15 = date<class 'datetime.date'>.today().replace(year=2025, month=1, day=15)9print(f"Today: {today2025-01-15}")1011# Date components12year→ 2025 = today.year202513month→ 1 = today.month114day→ 15 = today.day151516print("\nDate components:")17print(f"Year: {year2025}")18print(f"Month: {month1}")19print(f"Day: {day15}")2021# Day of week22# Monday is 0, Sunday is 623weekday→ 2 = today2025-01-15.weekday()24print(f"Day of week (0=Mon): {weekday2}")2526# ISO weekday (Monday is 1, Sunday is 7)27iso_weekday→ 3 = today2025-01-15.isoweekday()28print(f"ISO day of week (1=Mon): {iso_weekday3}")2930# Day name31day_name→ Wednesday = calendar.day_name[weekday]Wednesday32print(f"Day name: {day_nameWednesday}")3334# Month name35month_name→ January = calendar.month_name[month]January36print(f"Month name: {month_nameJanuary}")3738# ISO calendar (year, week, weekday)39iso→ datetime.IsoCalendarDate(year=2025, week=3, weekday=3) = today2025-01-15.isocalendar()40print(f"\nISO calendar:")41print(f"  Year: {iso[0]2025}")42print(f"  Week: {iso[1]3}")43print(f"  Weekday: {iso[2]3}")4445# Alternative access46print(f"  Year: {iso.year2025}")47print(f"  Week: {iso.week3}")48print(f"  Weekday: {iso.weekday3}")4950# Day of year51day_of_year→ 15 = today2025-01-15.timetuple().tm_yday52print(f"\nDay of year: {day_of_year15}")5354# Is leap year55def is_leap_year(year):56    return calendar.isleap(year)5758print(f"Is {year2025} a leap year: {is_leap_year(year)}")
    outputToday: 2025-01-15
    
    Date components:
    Year: 2025
    Month: 1
    Day: 15
    Day of week (0=Mon): 2
    ISO day of week (1=Mon): 3
    Day name: Wednesday
    Month name: January
    
    ISO calendar:
      Year: 2025
      Week: 3
      Weekday: 3
      Year: 2025
      Week: 3
      Weekday: 3
    
    Day of year: 15
  2. def is_leap_year(year):

    54# Is leap year55def is_leap_year(year2025):56    return calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.isleap(year2025)
  3. days_in_month ← 31

    58print(f"Is {year2025} a leap year: {is_leap_year(year)}")5960# Days in month61days_in_month→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(year2025, month1)[1]62print(f"Days in {month_nameJanuary}: {days_in_month31}")
    outputIs 2025 a leap year: False
    Days in January: 31
current_date Getting today's date and working with the system clock

Date Components

components.py
Replay: real traced execution (multi-file project)
# Date components

from datetime import date
import calendar

# Extract date components
d = date(2025, 1, 29)

print(f"Date: {d}")
print()

# Year, month, day
print(f"Year: {d.year}")
print(f"Month: {d.month}")
print(f"Day: {d.day}")

# Day of week
weekday = d.weekday()
iso_weekday = d.isoweekday()
print(f"\nWeekday (0=Mon): {weekday}")
print(f"ISO weekday (1=Mon): {iso_weekday}")
print(f"Day name: {calendar.day_name[weekday]}")

# Month name
print(f"\nMonth name: {calendar.month_name[d.month]}")
print(f"Short month: {calendar.month_abbr[d.month]}")

# ISO calendar
iso = d.isocalendar()
print(f"\nISO calendar:")
print(f"  Year: {iso.year}")
print(f"  Week number: {iso.week}")
print(f"  Weekday: {iso.weekday}")

# Day of year
timetuple = d.timetuple()
print(f"\nDay of year: {timetuple.tm_yday}")

# Convert to time tuple
print(f"\nTime tuple:")
print(f"  Year: {timetuple.tm_year}")
print(f"  Month: {timetuple.tm_mon}")
print(f"  Day: {timetuple.tm_mday}")
print(f"  Weekday: {timetuple.tm_wday}")
print(f"  Day of year: {timetuple.tm_yday}")

# Leap year check
is_leap = calendar.isleap(d.year)
print(f"\nIs {d.year} a leap year: {is_leap}")

# Days in month
days_in_month = calendar.monthrange(d.year, d.month)[1]
print(f"Days in {calendar.month_name[d.month]}: {days_in_month}")

# Ordinal (days since year 1)
ordinal = d.toordinal()
print(f"\nOrdinal: {ordinal}")

# CTime format
ctime = d.ctime()
print(f"Ctime: {ctime}")

# Multiple dates
print("\nWeek dates:")
monday = date(2025, 1, 27)
for i in range(7):
    from datetime import timedelta
    day = monday + timedelta(days=i)
    print(f"{day} is {calendar.day_name[day.weekday()]}")

  1. d ← 2025-01-29, weekday ← 2, iso_weekday ← 3, iso ← datetime.IsoCalendarDate(year=2025, week=5, weekday=3)

    6# Extract date components7d→ 2025-01-29 = date(2025, 1, 29)89print(f"Date: {d2025-01-29}")10print()1112# Year, month, day13print(f"Year: {d.year2025}")14print(f"Month: {d.month1}")15print(f"Day: {d.day29}")1617# Day of week18weekday→ 2 = d2025-01-29.weekday()19iso_weekday→ 3 = d2025-01-29.isoweekday()20print(f"\nWeekday (0=Mon): {weekday2}")21print(f"ISO weekday (1=Mon): {iso_weekday3}")22print(f"Day name: {calendar.day_name[weekday]Wednesday}")2324# Month name25print(f"\nMonth name: {calendar.month_name[d.month]January}")26print(f"Short month: {calendar.month_abbr[d.month]Jan}")2728# ISO calendar29iso→ datetime.IsoCalendarDate(year=2025, week=5, weekday=3) = d2025-01-29.isocalendar()30print(f"\nISO calendar:")31print(f"  Year: {iso.year2025}")32print(f"  Week number: {iso.week5}")33print(f"  Weekday: {iso.weekday3}")3435# Day of year36timetuple→ time.struct_time(tm_year=2025, tm_mon=1, tm_mday=29, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=29, tm_isdst=-1) = d2025-01-29.timetuple()37print(f"\nDay of year: {timetuple.tm_yday29}")3839# Convert to time tuple40print(f"\nTime tuple:")41print(f"  Year: {timetuple.tm_year2025}")42print(f"  Month: {timetuple.tm_mon1}")43print(f"  Day: {timetuple.tm_mday29}")44print(f"  Weekday: {timetuple.tm_wday2}")45print(f"  Day of year: {timetuple.tm_yday29}")4647# Leap year check48is_leap→ False = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.isleap(d.year2025)49print(f"\nIs {d.year2025} a leap year: {is_leapFalse}")5051# Days in month52days_in_month→ 31 = calendar<module 'calendar' from '/usr/local/lib/python3.12/calendar.py'>.monthrange(d.year2025, d.month1)[1]53print(f"Days in {calendar.month_name[d.month]January}: {days_in_month31}")5455# Ordinal (days since year 1)56ordinal→ 739280 = d2025-01-29.toordinal()57print(f"\nOrdinal: {ordinal739280}")5859# CTime format60ctime→ Wed Jan 29 00:00:00 2025 = d2025-01-29.ctime()61print(f"Ctime: {ctimeWed Jan 29 00:00:00 2025}")6263# Multiple dates64print("\nWeek dates:")65monday→ 2025-01-27 = date(2025, 1, 27)66for i in range(7):
    outputDate: 2025-01-29
    Year: 2025
    Month: 1
    Day: 29
    
    Weekday (0=Mon): 2
    ISO weekday (1=Mon): 3
    Day name: Wednesday
    
    Month name: January
    Short month: Jan
    
    ISO calendar:
      Year: 2025
      Week number: 5
      Weekday: 3
    
    Day of year: 29
    
    Time tuple:
      Year: 2025
      Month: 1
      Day: 29
      Weekday: 2
      Day of year: 29
    
    Is 2025 a leap year: False
    Days in January: 31
    
    Ordinal: 739280
    Ctime: Wed Jan 29 00:00:00 2025
    
    Week dates:
  2. day ← 2025-01-27

    pass 1 of 7
    65monday = date(2025, 1, 27)66for i0 in range(7):67    from datetime import timedelta68    day→ 2025-01-27 = monday2025-01-27 + timedelta(days=i0)69    print(f"{day2025-01-27} is {calendar.day_name⟨_localized_day A⟩[day.weekday()]}")
    output2025-01-27 is Monday
    All 7 passes — pass 1 is the card above
    passiday
    102025-01-27
    212025-01-28
    322025-01-29
    432025-01-30
    542025-01-31
    652025-02-01
    762025-02-02
date_components Accessing year, month, day, weekday, and calendar information

Comparing Dates

compare.py
Replay: real traced execution (multi-file project)
# Compare dates

from datetime import date

# Compare dates
date1 = date(2025, 1, 29)
date2 = date(2025, 2, 15)
date3 = date(2025, 1, 29)

print(f"Date 1: {date1}")
print(f"Date 2: {date2}")
print(f"Date 3: {date3}")
print()

# Comparison operators
print(f"date1 < date2: {date1 < date2}")
print(f"date1 > date2: {date1 > date2}")
print(f"date1 <= date2: {date1 <= date2}")
print(f"date1 >= date2: {date1 >= date2}")

# Equality
print(f"\ndate1 == date2: {date1 == date2}")
print(f"date1 == date3: {date1 == date3}")
print(f"date1 != date2: {date1 != date2}")

# Today comparisons
today = date.today().replace(year=2025, month=1, day=15)
print(f"\nToday: {today}")
print(f"date1 < today: {date1 < today}")
print(f"date1 > today: {date1 > today}")

# Find min/max
dates_list = [date1, date2, date3]
earliest = min(dates_list)
latest = max(dates_list)

print(f"\nEarliest: {earliest}")
print(f"Latest: {latest}")

# Check if in range
check = date(2025, 1, 31)
start = date(2025, 1, 1)
end = date(2025, 2, 1)

in_range = start <= check <= end
print(f"\n{check} is in range [{start}, {end}]: {in_range}")

# Sort dates
unsorted = [
    date(2025, 3, 15),
    date(2025, 1, 10),
    date(2025, 2, 20)
]

print("\nBefore sort:")
for d in unsorted:
    print(f"  {d}")

sorted_dates = sorted(unsorted)

print("After sort:")
for d in sorted_dates:
    print(f"  {d}")

# Find closest date to today
candidates = [
    date(2025, 2, 1),
    date(2025, 6, 15),
    date(2025, 12, 25)
]

closest = min(candidates, key=lambda d: abs((d - today).days))
print(f"\nClosest date to today: {closest}")

# Filter past dates
all_dates = [
    date(2024, 1, 1),
    date(2025, 1, 1),
    date(2026, 1, 1)
]

past_dates = [d for d in all_dates if d < today]
future_dates = [d for d in all_dates if d > today]

print(f"\nPast dates: {past_dates}")
print(f"Future dates: {future_dates}")

# Check if date is today
print(f"\n{date1} is today: {date1 == today}")
print(f"{today} is today: {today == date.today().replace(year=2025, month=1, day=15)}")

  1. date1 ← 2025-01-29, date2 ← 2025-02-15, date3 ← 2025-01-29, today ← 2025-01-15

    5# Compare dates6date1→ 2025-01-29 = date(2025, 1, 29)7date2→ 2025-02-15 = date(2025, 2, 15)8date3→ 2025-01-29 = date(2025, 1, 29)910print(f"Date 1: {date12025-01-29}")11print(f"Date 2: {date22025-02-15}")12print(f"Date 3: {date32025-01-29}")13print()1415# Comparison operators16print(f"date1 < date2: {date12025-01-29 < date22025-02-15}")17print(f"date1 > date2: {date12025-01-29 > date22025-02-15}")18print(f"date1 <= date2: {date12025-01-29 <= date22025-02-15}")19print(f"date1 >= date2: {date12025-01-29 >= date22025-02-15}")2021# Equality22print(f"\ndate1 == date2: {date12025-01-29 == date22025-02-15}")23print(f"date1 == date3: {date12025-01-29 == date32025-01-29}")24print(f"date1 != date2: {date12025-01-29 != date22025-02-15}")2526# Today comparisons27today→ 2025-01-15 = date<class 'datetime.date'>.today().replace(year=2025, month=1, day=15)28print(f"\nToday: {today2025-01-15}")29print(f"date1 < today: {date12025-01-29 < today2025-01-15}")30print(f"date1 > today: {date12025-01-29 > today2025-01-15}")3132# Find min/max33dates_list→ [datetime.date(2025, 1, 29), datetime.date(2025, 2, 15), datetime.date(2025, 1, 29)] = [date12025-01-29, date22025-02-15, date32025-01-29]34earliest→ 2025-01-29 = min(dates_list[datetime.date(2025, 1, 29), datetime.date(2025, 2, 15), datetime.date(2025, 1, 29)])35latest→ 2025-02-15 = max(dates_list[datetime.date(2025, 1, 29), datetime.date(2025, 2, 15), datetime.date(2025, 1, 29)])3637print(f"\nEarliest: {earliest2025-01-29}")38print(f"Latest: {latest2025-02-15}")3940# Check if in range41check→ 2025-01-31 = date(2025, 1, 31)42start→ 2025-01-01 = date(2025, 1, 1)43end→ 2025-02-01 = date(2025, 2, 1)4445in_range→ True = start2025-01-01 <= check2025-01-31 <= end2025-02-0146print(f"\n{check2025-01-31} is in range [{start2025-01-01}, {end2025-02-01}]: {in_rangeTrue}")4748# Sort dates49unsorted→ [datetime.date(2025, 3, 15), datetime.date(2025, 1, 10), datetime.date(2025, 2, 20)] = [50    date(2025, 3, 15),51    date(2025, 1, 10),52    date(2025, 2, 20)53]5455print("\nBefore sort:")56for d in unsorted:
    outputDate 1: 2025-01-29
    Date 2: 2025-02-15
    Date 3: 2025-01-29
    date1 < date2: True
    date1 > date2: False
    date1 <= date2: True
    date1 >= date2: False
    
    date1 == date2: False
    date1 == date3: True
    date1 != date2: True
    
    Today: 2025-01-15
    date1 < today: False
    date1 > today: True
    
    Earliest: 2025-01-29
    Latest: 2025-02-15
    
    2025-01-31 is in range [2025-01-01, 2025-02-01]: True
    
    Before sort:
  2. for d in unsorted:

    pass 1 of 3
    55print("\nBefore sort:")56for d2025-03-15 in unsorted[datetime.date(2025, 3, 15), datetime.date(2025, 1, 10), datetime.date(2025, 2, 20)]:57    print(f"  {d2025-03-15}")
    output  2025-03-15
    All 3 passes — pass 1 is the card above
    passd
    12025-03-15
    22025-01-10
    32025-02-20
  3. sorted_dates ← [datetime.date(2025, 1, 10), datetime.date(2025, 2, 20), datetime.date(2025, 3, 15)]

    59sorted_dates→ [datetime.date(2025, 1, 10), datetime.date(2025, 2, 20), datetime.date(2025, 3, 15)] = sorted(unsorted[datetime.date(2025, 3, 15), datetime.date(2025, 1, 10), datetime.date(2025, 2, 20)])6061print("After sort:")62for d in sorted_dates:
    outputAfter sort:
  4. for d in sorted_dates:

    pass 1 of 3
    61print("After sort:")62for d2025-01-10 in sorted_dates[datetime.date(2025, 1, 10), datetime.date(2025, 2, 20), datetime.date(2025, 3, 15)]:63    print(f"  {d2025-01-10}")
    output  2025-01-10
    All 3 passes — pass 1 is the card above
    passd
    12025-01-10
    22025-02-20
    32025-03-15
  5. candidates ← [datetime.date(2025, 2, 1), datetime.date(2025, 6, 15), datetime.date(2025, 12, 25)]

    65# Find closest date to today66candidates→ [datetime.date(2025, 2, 1), datetime.date(2025, 6, 15), datetime.date(2025, 12, 25)] = [67    date(2025, 2, 1),68    date(2025, 6, 15),69    date(2025, 12, 25)70]7172closest→ 2025-02-01 = min(candidates[datetime.date(2025, 2, 1), datetime.date(2025, 6, 15), datetime.date(2025, 12, 25)], key=lambda d: abs((d - today).days))73print(f"\nClosest date to today: {closest2025-02-01}")7475# Filter past dates76all_dates→ [datetime.date(2024, 1, 1), datetime.date(2025, 1, 1), datetime.date(2026, 1, 1)] = [77    date(2024, 1, 1),78    date(2025, 1, 1),79    date(2026, 1, 1)80]8182past_dates→ [datetime.date(2024, 1, 1), datetime.date(2025, 1, 1)] = [d for d in all_dates[datetime.date(2024, 1, 1), datetime.date(2025, 1, 1), datetime.date(2026, 1, 1)] if d < today2025-01-15]83future_dates→ [datetime.date(2026, 1, 1)] = [d for d in all_dates[datetime.date(2024, 1, 1), datetime.date(2025, 1, 1), datetime.date(2026, 1, 1)] if d > today2025-01-15]8485print(f"\nPast dates: {past_dates[datetime.date(2024, 1, 1), datetime.date(2025, 1, 1)]}")86print(f"Future dates: {future_dates[datetime.date(2026, 1, 1)]}")8788# Check if date is today89print(f"\n{date12025-01-29} is today: {date1 == today2025-01-15}")90print(f"{today2025-01-15} is today: {today == date<class 'datetime.date'>.today().replace(year=2025, month=1, day=15)}")
    output
    Closest date to today: 2025-02-01
    
    Past dates: [datetime.date(2024, 1, 1), datetime.date(2025, 1, 1)]
    Future dates: [datetime.date(2026, 1, 1)]
    
    2025-01-29 is today: False
    2025-01-15 is today: True
date_comparison Comparing dates and checking chronological order

Parsing Dates

iso
parse.py
Replay: real traced execution (multi-file project)
# Parse date string

from datetime import date, datetime

# Parse date strings
# Parse ISO format (YYYY-MM-DD)
iso = "2025-01-29"
date1 = date.fromisoformat(iso)
print(f"Parsed ISO: {date1}")

# Parse with strptime (string parse time)
custom1 = "29/01/2025"
date2 = datetime.strptime(custom1, "%d/%m/%Y").date()
print(f"Parsed {custom1}: {date2}")

# Parse various formats
date_strings = [
    ("2025-12-25", "%Y-%m-%d"),
    ("25/12/2025", "%d/%m/%Y"),
    ("12-25-2025", "%m-%d-%Y"),
    ("Dec 25, 2025", "%b %d, %Y"),
    ("December 25, 2025", "%B %d, %Y")
]

print("\nParse various formats:")
for date_str, fmt in date_strings:
    d = datetime.strptime(date_str, fmt).date()
    print(f"{date_str} -> {d}")

# Handle parse errors
print("\nHandle parse errors:")
test_dates = [
    "2025-01-29",
    "2025-13-01",   # invalid month
    "2025-02-30",   # invalid day
    "not-a-date"
]

for date_str in test_dates:
    try:
        d = date.fromisoformat(date_str)
        print(f"{date_str} -> {d}")
    except ValueError as e:
        print(f"{date_str} -> ERROR: {e}")

# Safe parse function
def safe_parse_date(date_str, fmt="%Y-%m-%d"):
    """Parse date string with error handling"""
    try:
        return datetime.strptime(date_str, fmt).date()
    except ValueError:
        print(f"Invalid date: {date_str}")
        return None

print("\nSafe parse:")
print(safe_parse_date("2025-01-29"))
print(safe_parse_date("invalid"))

# Parse with different separators
date3 = "2025/01/29"
parsed3 = datetime.strptime(date3, "%Y/%m/%d").date()
print(f"\nParsed {date3}: {parsed3}")

# Parse with text month
date4 = "January 29, 2025"
parsed4 = datetime.strptime(date4, "%B %d, %Y").date()
print(f"Parsed {date4}: {parsed4}")

# Parse ordinal format
ordinal_str = "2025-029"  # 29th day of 2025
parsed_ordinal = datetime.strptime(ordinal_str, "%Y-%j").date()
print(f"\nParsed ordinal {ordinal_str}: {parsed_ordinal}")

# Format codes reference
print("\nCommon format codes:")
print("  %Y - 4-digit year (2025)")
print("  %m - 2-digit month (01-12)")
print("  %d - 2-digit day (01-31)")
print("  %b - Short month (Jan)")
print("  %B - Full month (January)")
print("  %j - Day of year (001-366)")

# Parse date string

from datetime import date, datetime

# Parse date strings
# Parse ISO format (YYYY-MM-DD)
iso = "2024-02-29"
date1 = date.fromisoformat(iso)
print(f"Parsed ISO: {date1}")

# Parse with strptime (string parse time)
custom1 = "29/01/2025"
date2 = datetime.strptime(custom1, "%d/%m/%Y").date()
print(f"Parsed {custom1}: {date2}")

# Parse various formats
date_strings = [
    ("2025-12-25", "%Y-%m-%d"),
    ("25/12/2025", "%d/%m/%Y"),
    ("12-25-2025", "%m-%d-%Y"),
    ("Dec 25, 2025", "%b %d, %Y"),
    ("December 25, 2025", "%B %d, %Y")
]

print("\nParse various formats:")
for date_str, fmt in date_strings:
    d = datetime.strptime(date_str, fmt).date()
    print(f"{date_str} -> {d}")

# Handle parse errors
print("\nHandle parse errors:")
test_dates = [
    "2025-01-29",
    "2025-13-01",   # invalid month
    "2025-02-30",   # invalid day
    "not-a-date"
]

for date_str in test_dates:
    try:
        d = date.fromisoformat(date_str)
        print(f"{date_str} -> {d}")
    except ValueError as e:
        print(f"{date_str} -> ERROR: {e}")

# Safe parse function
def safe_parse_date(date_str, fmt="%Y-%m-%d"):
    """Parse date string with error handling"""
    try:
        return datetime.strptime(date_str, fmt).date()
    except ValueError:
        print(f"Invalid date: {date_str}")
        return None

print("\nSafe parse:")
print(safe_parse_date("2025-01-29"))
print(safe_parse_date("invalid"))

# Parse with different separators
date3 = "2025/01/29"
parsed3 = datetime.strptime(date3, "%Y/%m/%d").date()
print(f"\nParsed {date3}: {parsed3}")

# Parse with text month
date4 = "January 29, 2025"
parsed4 = datetime.strptime(date4, "%B %d, %Y").date()
print(f"Parsed {date4}: {parsed4}")

# Parse ordinal format
ordinal_str = "2025-029"  # 29th day of 2025
parsed_ordinal = datetime.strptime(ordinal_str, "%Y-%j").date()
print(f"\nParsed ordinal {ordinal_str}: {parsed_ordinal}")

# Format codes reference
print("\nCommon format codes:")
print("  %Y - 4-digit year (2025)")
print("  %m - 2-digit month (01-12)")
print("  %d - 2-digit day (01-31)")
print("  %b - Short month (Jan)")
print("  %B - Full month (January)")
print("  %j - Day of year (001-366)")

# Parse date string

from datetime import date, datetime

# Parse date strings
# Parse ISO format (YYYY-MM-DD)
iso = "2026-06-15"
date1 = date.fromisoformat(iso)
print(f"Parsed ISO: {date1}")

# Parse with strptime (string parse time)
custom1 = "29/01/2025"
date2 = datetime.strptime(custom1, "%d/%m/%Y").date()
print(f"Parsed {custom1}: {date2}")

# Parse various formats
date_strings = [
    ("2025-12-25", "%Y-%m-%d"),
    ("25/12/2025", "%d/%m/%Y"),
    ("12-25-2025", "%m-%d-%Y"),
    ("Dec 25, 2025", "%b %d, %Y"),
    ("December 25, 2025", "%B %d, %Y")
]

print("\nParse various formats:")
for date_str, fmt in date_strings:
    d = datetime.strptime(date_str, fmt).date()
    print(f"{date_str} -> {d}")

# Handle parse errors
print("\nHandle parse errors:")
test_dates = [
    "2025-01-29",
    "2025-13-01",   # invalid month
    "2025-02-30",   # invalid day
    "not-a-date"
]

for date_str in test_dates:
    try:
        d = date.fromisoformat(date_str)
        print(f"{date_str} -> {d}")
    except ValueError as e:
        print(f"{date_str} -> ERROR: {e}")

# Safe parse function
def safe_parse_date(date_str, fmt="%Y-%m-%d"):
    """Parse date string with error handling"""
    try:
        return datetime.strptime(date_str, fmt).date()
    except ValueError:
        print(f"Invalid date: {date_str}")
        return None

print("\nSafe parse:")
print(safe_parse_date("2025-01-29"))
print(safe_parse_date("invalid"))

# Parse with different separators
date3 = "2025/01/29"
parsed3 = datetime.strptime(date3, "%Y/%m/%d").date()
print(f"\nParsed {date3}: {parsed3}")

# Parse with text month
date4 = "January 29, 2025"
parsed4 = datetime.strptime(date4, "%B %d, %Y").date()
print(f"Parsed {date4}: {parsed4}")

# Parse ordinal format
ordinal_str = "2025-029"  # 29th day of 2025
parsed_ordinal = datetime.strptime(ordinal_str, "%Y-%j").date()
print(f"\nParsed ordinal {ordinal_str}: {parsed_ordinal}")

# Format codes reference
print("\nCommon format codes:")
print("  %Y - 4-digit year (2025)")
print("  %m - 2-digit month (01-12)")
print("  %d - 2-digit day (01-31)")
print("  %b - Short month (Jan)")
print("  %B - Full month (January)")
print("  %j - Day of year (001-366)")

  1. iso ← 2025-01-29, date1 ← 2025-01-29, custom1 ← 29/01/2025, date2 ← 2025-01-29

    6# Parse ISO format (YYYY-MM-DD)7iso→ 2025-01-29 = "2025-01-29"  #@iso="2024-02-29", "2026-06-15"8date1→ 2025-01-29 = date<class 'datetime.date'>.fromisoformat(iso2025-01-29)9print(f"Parsed ISO: {date12025-01-29}")1011# Parse with strptime (string parse time)12custom1→ 29/01/2025 = "29/01/2025"13date2→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(custom129/01/2025, "%d/%m/%Y").date()14print(f"Parsed {custom129/01/2025}: {date22025-01-29}")1516# Parse various formats17date_strings→ [('2025-12-25', '%Y-%m-%d'), ('25/12/2025', '%d/%m/%Y'), ('12-25-2025', '%m-%d-%Y'), ('Dec 25, 2025', '%b %d, %Y'), ('December 25, 2025', '%B %d, %Y')] = [18    ("2025-12-25", "%Y-%m-%d"),19    ("25/12/2025", "%d/%m/%Y"),20    ("12-25-2025", "%m-%d-%Y"),21    ("Dec 25, 2025", "%b %d, %Y"),22    ("December 25, 2025", "%B %d, %Y")23]2425print("\nParse various formats:")26for date_str, fmt in date_strings:
    outputParsed ISO: 2025-01-29
    Parsed 29/01/2025: 2025-01-29
    
    Parse various formats:
  2. d ← 2025-12-25

    pass 1 of 5
    25print("\nParse various formats:")26for date_str2025-12-25, fmt%Y-%m-%d in date_strings[('2025-12-25', '%Y-%m-%d'), ('25/12/2025', '%d/%m/%Y'), ('12-25-2025', '%m-%d-%Y'), ('Dec 25, 2025', '%b %d, %Y'), ('December 25, 2025', '%B %d, %Y')]:27    d→ 2025-12-25 = datetime<class 'datetime.datetime'>.strptime(date_str2025-12-25, fmt%Y-%m-%d).date()28    print(f"{date_str2025-12-25} -> {d2025-12-25}")
    output2025-12-25 -> 2025-12-25
    All 5 passes — pass 1 is the card above
    passdate_strfmtd
    12025-12-25%Y-%m-%d2025-12-25
    225/12/2025%d/%m/%Y2025-12-25
    312-25-2025%m-%d-%Y2025-12-25
    4Dec 25, 2025%b %d, %Y2025-12-25
    5December 25, 2025%B %d, %Y2025-12-25
  3. test_dates ← ['2025-01-29', '2025-13-01', '2025-02-30', 'not-a-date']

    30# Handle parse errors31print("\nHandle parse errors:")32test_dates→ ['2025-01-29', '2025-13-01', '2025-02-30', 'not-a-date'] = [33    "2025-01-29",34    "2025-13-01",   # invalid month35    "2025-02-30",   # invalid day36    "not-a-date"37]
    output
    Handle parse errors:
  4. for date_str in test_dates:

    pass 1 of 4
    39for date_str2025-01-29 in test_dates['2025-01-29', '2025-13-01', '2025-02-30', 'not-a-date']:40    try:41        d = date.fromisoformat(date_str)
    All 4 passes — pass 1 is the card above
    passdate_str
    12025-01-29
    22025-13-01
    32025-02-30
    4not-a-date
  5. d ← 2025-01-29

    pass 1 of 4
    39for date_str in test_dates:40    try:41        d→ 2025-01-29 = date<class 'datetime.date'>.fromisoformat(date_str2025-01-29)42        print(f"{date_str2025-01-29} -> {d2025-01-29}")43    except ValueError as e:
    output2025-01-29 -> 2025-01-29
    All 4 passes — pass 1 is the card above
    passdate_strd
    12025-01-292025-01-29
    22025-13-01
    32025-02-30
    4not-a-date
  6. except ValueError as e:

    pass 1 of 3
    42    print(f"{date_str} -> {d}")43except ValueError as e:44    print(f"{date_str2025-13-01} -> ERROR: {emonth must be in 1..12}")
    output2025-13-01 -> ERROR: month must be in 1..12
    2025-13-01 -> ERROR: month must be in 1..12
    All 3 passes — pass 1 is the card above
    passdate_stre
    12025-13-01month must be in 1..12
    22025-02-30day is out of range for month
    3not-a-dateInvalid isoformat string: 'not-a-date'
  7. print(" Safe parse:")

    55print("\nSafe parse:")56print(safe_parse_date("2025-01-29"))57print(safe_parse_date("invalid"))
    output
    Safe parse:
  8. def safe_parse_date(date_str, fmt="%Y-%m-%d"):

    pass 1 of 2
    46# Safe parse function47def safe_parse_date(date_str2025-01-29, fmt%Y-%m-%d="%Y-%m-%d"):48    """Parse date string with error handling"""49    try:
  9. try:

    pass 1 of 2
    48"""Parse date string with error handling"""49try:50    return datetime<class 'datetime.datetime'>.strptime(date_str2025-01-29, fmt%Y-%m-%d).date()51except ValueError:
  10. print(safe_parse_date("2025-01-29"))

    55print("\nSafe parse:")56print(safe_parse_date("2025-01-29"))57print(safe_parse_date("invalid"))
    output2025-01-29
  11. def safe_parse_date(date_str, fmt="%Y-%m-%d"):

    pass 2 of 2
    46# Safe parse function47def safe_parse_date(date_strinvalid, fmt%Y-%m-%d="%Y-%m-%d"):48    """Parse date string with error handling"""49    try:
  12. try:

    pass 2 of 2
    48"""Parse date string with error handling"""49try:50    return datetime<class 'datetime.datetime'>.strptime(date_strinvalid, fmt%Y-%m-%d).date()51except ValueError:
  13. except ValueError:

    50    return datetime.strptime(date_str, fmt).date()51except ValueError:52    print(f"Invalid date: {date_strinvalid}")53    return None
    outputInvalid date: invalid
  14. date3 ← 2025/01/29, parsed3 ← 2025-01-29, date4 ← January 29, 2025

    56print(safe_parse_date("2025-01-29"))57print(safe_parse_date("invalid"))5859# Parse with different separators60date3→ 2025/01/29 = "2025/01/29"61parsed3→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(date32025/01/29, "%Y/%m/%d").date()62print(f"\nParsed {date32025/01/29}: {parsed32025-01-29}")6364# Parse with text month65date4→ January 29, 2025 = "January 29, 2025"66parsed4→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(date4January 29, 2025, "%B %d, %Y").date()67print(f"Parsed {date4January 29, 2025}: {parsed42025-01-29}")6869# Parse ordinal format70ordinal_str→ 2025-029 = "2025-029"  # 29th day of 202571parsed_ordinal→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(ordinal_str2025-029, "%Y-%j").date()72print(f"\nParsed ordinal {ordinal_str2025-029}: {parsed_ordinal2025-01-29}")7374# Format codes reference75print("\nCommon format codes:")76print("  %Y - 4-digit year (2025)")77print("  %m - 2-digit month (01-12)")78print("  %d - 2-digit day (01-31)")79print("  %b - Short month (Jan)")80print("  %B - Full month (January)")81print("  %j - Day of year (001-366)")
    outputNone
    
    Parsed 2025/01/29: 2025-01-29
    Parsed January 29, 2025: 2025-01-29
    
    Parsed ordinal 2025-029: 2025-01-29
    
    Common format codes:
      %Y - 4-digit year (2025)
      %m - 2-digit month (01-12)
      %d - 2-digit day (01-31)
      %b - Short month (Jan)
      %B - Full month (January)
      %j - Day of year (001-366)
  1. iso ← 2024-02-29, date1 ← 2024-02-29, custom1 ← 29/01/2025, date2 ← 2025-01-29

    6# Parse ISO format (YYYY-MM-DD)7iso→ 2024-02-29 = "2024-02-29"8date1→ 2024-02-29 = date<class 'datetime.date'>.fromisoformat(iso2024-02-29)9print(f"Parsed ISO: {date12024-02-29}")1011# Parse with strptime (string parse time)12custom1→ 29/01/2025 = "29/01/2025"13date2→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(custom129/01/2025, "%d/%m/%Y").date()14print(f"Parsed {custom129/01/2025}: {date22025-01-29}")1516# Parse various formats17date_strings→ [('2025-12-25', '%Y-%m-%d'), ('25/12/2025', '%d/%m/%Y'), ('12-25-2025', '%m-%d-%Y'), ('Dec 25, 2025', '%b %d, %Y'), ('December 25, 2025', '%B %d, %Y')] = [18    ("2025-12-25", "%Y-%m-%d"),19    ("25/12/2025", "%d/%m/%Y"),20    ("12-25-2025", "%m-%d-%Y"),21    ("Dec 25, 2025", "%b %d, %Y"),22    ("December 25, 2025", "%B %d, %Y")23]2425print("\nParse various formats:")26for date_str, fmt in date_strings:
    outputParsed ISO: 2024-02-29
    Parsed 29/01/2025: 2025-01-29
    
    Parse various formats:
  2. d ← 2025-12-25

    pass 1 of 5
    25print("\nParse various formats:")26for date_str2025-12-25, fmt%Y-%m-%d in date_strings[('2025-12-25', '%Y-%m-%d'), ('25/12/2025', '%d/%m/%Y'), ('12-25-2025', '%m-%d-%Y'), ('Dec 25, 2025', '%b %d, %Y'), ('December 25, 2025', '%B %d, %Y')]:27    d→ 2025-12-25 = datetime<class 'datetime.datetime'>.strptime(date_str2025-12-25, fmt%Y-%m-%d).date()28    print(f"{date_str2025-12-25} -> {d2025-12-25}")
    output2025-12-25 -> 2025-12-25
    All 5 passes — pass 1 is the card above
    passdate_strfmtd
    12025-12-25%Y-%m-%d2025-12-25
    225/12/2025%d/%m/%Y2025-12-25
    312-25-2025%m-%d-%Y2025-12-25
    4Dec 25, 2025%b %d, %Y2025-12-25
    5December 25, 2025%B %d, %Y2025-12-25
  3. test_dates ← ['2025-01-29', '2025-13-01', '2025-02-30', 'not-a-date']

    30# Handle parse errors31print("\nHandle parse errors:")32test_dates→ ['2025-01-29', '2025-13-01', '2025-02-30', 'not-a-date'] = [33    "2025-01-29",34    "2025-13-01",   # invalid month35    "2025-02-30",   # invalid day36    "not-a-date"37]
    output
    Handle parse errors:
  4. for date_str in test_dates:

    pass 1 of 4
    39for date_str2025-01-29 in test_dates['2025-01-29', '2025-13-01', '2025-02-30', 'not-a-date']:40    try:41        d = date.fromisoformat(date_str)
    All 4 passes — pass 1 is the card above
    passdate_str
    12025-01-29
    22025-13-01
    32025-02-30
    4not-a-date
  5. d ← 2025-01-29

    pass 1 of 4
    39for date_str in test_dates:40    try:41        d→ 2025-01-29 = date<class 'datetime.date'>.fromisoformat(date_str2025-01-29)42        print(f"{date_str2025-01-29} -> {d2025-01-29}")43    except ValueError as e:
    output2025-01-29 -> 2025-01-29
    All 4 passes — pass 1 is the card above
    passdate_strd
    12025-01-292025-01-29
    22025-13-01
    32025-02-30
    4not-a-date
  6. except ValueError as e:

    pass 1 of 3
    42    print(f"{date_str} -> {d}")43except ValueError as e:44    print(f"{date_str2025-13-01} -> ERROR: {emonth must be in 1..12}")
    output2025-13-01 -> ERROR: month must be in 1..12
    2025-13-01 -> ERROR: month must be in 1..12
    All 3 passes — pass 1 is the card above
    passdate_stre
    12025-13-01month must be in 1..12
    22025-02-30day is out of range for month
    3not-a-dateInvalid isoformat string: 'not-a-date'
  7. print(" Safe parse:")

    55print("\nSafe parse:")56print(safe_parse_date("2025-01-29"))57print(safe_parse_date("invalid"))
    output
    Safe parse:
  8. def safe_parse_date(date_str, fmt="%Y-%m-%d"):

    pass 1 of 2
    46# Safe parse function47def safe_parse_date(date_str2025-01-29, fmt%Y-%m-%d="%Y-%m-%d"):48    """Parse date string with error handling"""49    try:
  9. try:

    pass 1 of 2
    48"""Parse date string with error handling"""49try:50    return datetime<class 'datetime.datetime'>.strptime(date_str2025-01-29, fmt%Y-%m-%d).date()51except ValueError:
  10. print(safe_parse_date("2025-01-29"))

    55print("\nSafe parse:")56print(safe_parse_date("2025-01-29"))57print(safe_parse_date("invalid"))
    output2025-01-29
  11. def safe_parse_date(date_str, fmt="%Y-%m-%d"):

    pass 2 of 2
    46# Safe parse function47def safe_parse_date(date_strinvalid, fmt%Y-%m-%d="%Y-%m-%d"):48    """Parse date string with error handling"""49    try:
  12. try:

    pass 2 of 2
    48"""Parse date string with error handling"""49try:50    return datetime<class 'datetime.datetime'>.strptime(date_strinvalid, fmt%Y-%m-%d).date()51except ValueError:
  13. except ValueError:

    50    return datetime.strptime(date_str, fmt).date()51except ValueError:52    print(f"Invalid date: {date_strinvalid}")53    return None
    outputInvalid date: invalid
  14. date3 ← 2025/01/29, parsed3 ← 2025-01-29, date4 ← January 29, 2025

    56print(safe_parse_date("2025-01-29"))57print(safe_parse_date("invalid"))5859# Parse with different separators60date3→ 2025/01/29 = "2025/01/29"61parsed3→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(date32025/01/29, "%Y/%m/%d").date()62print(f"\nParsed {date32025/01/29}: {parsed32025-01-29}")6364# Parse with text month65date4→ January 29, 2025 = "January 29, 2025"66parsed4→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(date4January 29, 2025, "%B %d, %Y").date()67print(f"Parsed {date4January 29, 2025}: {parsed42025-01-29}")6869# Parse ordinal format70ordinal_str→ 2025-029 = "2025-029"  # 29th day of 202571parsed_ordinal→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(ordinal_str2025-029, "%Y-%j").date()72print(f"\nParsed ordinal {ordinal_str2025-029}: {parsed_ordinal2025-01-29}")7374# Format codes reference75print("\nCommon format codes:")76print("  %Y - 4-digit year (2025)")77print("  %m - 2-digit month (01-12)")78print("  %d - 2-digit day (01-31)")79print("  %b - Short month (Jan)")80print("  %B - Full month (January)")81print("  %j - Day of year (001-366)")
    outputNone
    
    Parsed 2025/01/29: 2025-01-29
    Parsed January 29, 2025: 2025-01-29
    
    Parsed ordinal 2025-029: 2025-01-29
    
    Common format codes:
      %Y - 4-digit year (2025)
      %m - 2-digit month (01-12)
      %d - 2-digit day (01-31)
      %b - Short month (Jan)
      %B - Full month (January)
      %j - Day of year (001-366)
  1. iso ← 2026-06-15, date1 ← 2026-06-15, custom1 ← 29/01/2025, date2 ← 2025-01-29

    6# Parse ISO format (YYYY-MM-DD)7iso→ 2026-06-15 = "2026-06-15"8date1→ 2026-06-15 = date<class 'datetime.date'>.fromisoformat(iso2026-06-15)9print(f"Parsed ISO: {date12026-06-15}")1011# Parse with strptime (string parse time)12custom1→ 29/01/2025 = "29/01/2025"13date2→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(custom129/01/2025, "%d/%m/%Y").date()14print(f"Parsed {custom129/01/2025}: {date22025-01-29}")1516# Parse various formats17date_strings→ [('2025-12-25', '%Y-%m-%d'), ('25/12/2025', '%d/%m/%Y'), ('12-25-2025', '%m-%d-%Y'), ('Dec 25, 2025', '%b %d, %Y'), ('December 25, 2025', '%B %d, %Y')] = [18    ("2025-12-25", "%Y-%m-%d"),19    ("25/12/2025", "%d/%m/%Y"),20    ("12-25-2025", "%m-%d-%Y"),21    ("Dec 25, 2025", "%b %d, %Y"),22    ("December 25, 2025", "%B %d, %Y")23]2425print("\nParse various formats:")26for date_str, fmt in date_strings:
    outputParsed ISO: 2026-06-15
    Parsed 29/01/2025: 2025-01-29
    
    Parse various formats:
  2. d ← 2025-12-25

    pass 1 of 5
    25print("\nParse various formats:")26for date_str2025-12-25, fmt%Y-%m-%d in date_strings[('2025-12-25', '%Y-%m-%d'), ('25/12/2025', '%d/%m/%Y'), ('12-25-2025', '%m-%d-%Y'), ('Dec 25, 2025', '%b %d, %Y'), ('December 25, 2025', '%B %d, %Y')]:27    d→ 2025-12-25 = datetime<class 'datetime.datetime'>.strptime(date_str2025-12-25, fmt%Y-%m-%d).date()28    print(f"{date_str2025-12-25} -> {d2025-12-25}")
    output2025-12-25 -> 2025-12-25
    All 5 passes — pass 1 is the card above
    passdate_strfmtd
    12025-12-25%Y-%m-%d2025-12-25
    225/12/2025%d/%m/%Y2025-12-25
    312-25-2025%m-%d-%Y2025-12-25
    4Dec 25, 2025%b %d, %Y2025-12-25
    5December 25, 2025%B %d, %Y2025-12-25
  3. test_dates ← ['2025-01-29', '2025-13-01', '2025-02-30', 'not-a-date']

    30# Handle parse errors31print("\nHandle parse errors:")32test_dates→ ['2025-01-29', '2025-13-01', '2025-02-30', 'not-a-date'] = [33    "2025-01-29",34    "2025-13-01",   # invalid month35    "2025-02-30",   # invalid day36    "not-a-date"37]
    output
    Handle parse errors:
  4. for date_str in test_dates:

    pass 1 of 4
    39for date_str2025-01-29 in test_dates['2025-01-29', '2025-13-01', '2025-02-30', 'not-a-date']:40    try:41        d = date.fromisoformat(date_str)
    All 4 passes — pass 1 is the card above
    passdate_str
    12025-01-29
    22025-13-01
    32025-02-30
    4not-a-date
  5. d ← 2025-01-29

    pass 1 of 4
    39for date_str in test_dates:40    try:41        d→ 2025-01-29 = date<class 'datetime.date'>.fromisoformat(date_str2025-01-29)42        print(f"{date_str2025-01-29} -> {d2025-01-29}")43    except ValueError as e:
    output2025-01-29 -> 2025-01-29
    All 4 passes — pass 1 is the card above
    passdate_strd
    12025-01-292025-01-29
    22025-13-01
    32025-02-30
    4not-a-date
  6. except ValueError as e:

    pass 1 of 3
    42    print(f"{date_str} -> {d}")43except ValueError as e:44    print(f"{date_str2025-13-01} -> ERROR: {emonth must be in 1..12}")
    output2025-13-01 -> ERROR: month must be in 1..12
    2025-13-01 -> ERROR: month must be in 1..12
    All 3 passes — pass 1 is the card above
    passdate_stre
    12025-13-01month must be in 1..12
    22025-02-30day is out of range for month
    3not-a-dateInvalid isoformat string: 'not-a-date'
  7. print(" Safe parse:")

    55print("\nSafe parse:")56print(safe_parse_date("2025-01-29"))57print(safe_parse_date("invalid"))
    output
    Safe parse:
  8. def safe_parse_date(date_str, fmt="%Y-%m-%d"):

    pass 1 of 2
    46# Safe parse function47def safe_parse_date(date_str2025-01-29, fmt%Y-%m-%d="%Y-%m-%d"):48    """Parse date string with error handling"""49    try:
  9. try:

    pass 1 of 2
    48"""Parse date string with error handling"""49try:50    return datetime<class 'datetime.datetime'>.strptime(date_str2025-01-29, fmt%Y-%m-%d).date()51except ValueError:
  10. print(safe_parse_date("2025-01-29"))

    55print("\nSafe parse:")56print(safe_parse_date("2025-01-29"))57print(safe_parse_date("invalid"))
    output2025-01-29
  11. def safe_parse_date(date_str, fmt="%Y-%m-%d"):

    pass 2 of 2
    46# Safe parse function47def safe_parse_date(date_strinvalid, fmt%Y-%m-%d="%Y-%m-%d"):48    """Parse date string with error handling"""49    try:
  12. try:

    pass 2 of 2
    48"""Parse date string with error handling"""49try:50    return datetime<class 'datetime.datetime'>.strptime(date_strinvalid, fmt%Y-%m-%d).date()51except ValueError:
  13. except ValueError:

    50    return datetime.strptime(date_str, fmt).date()51except ValueError:52    print(f"Invalid date: {date_strinvalid}")53    return None
    outputInvalid date: invalid
  14. date3 ← 2025/01/29, parsed3 ← 2025-01-29, date4 ← January 29, 2025

    56print(safe_parse_date("2025-01-29"))57print(safe_parse_date("invalid"))5859# Parse with different separators60date3→ 2025/01/29 = "2025/01/29"61parsed3→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(date32025/01/29, "%Y/%m/%d").date()62print(f"\nParsed {date32025/01/29}: {parsed32025-01-29}")6364# Parse with text month65date4→ January 29, 2025 = "January 29, 2025"66parsed4→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(date4January 29, 2025, "%B %d, %Y").date()67print(f"Parsed {date4January 29, 2025}: {parsed42025-01-29}")6869# Parse ordinal format70ordinal_str→ 2025-029 = "2025-029"  # 29th day of 202571parsed_ordinal→ 2025-01-29 = datetime<class 'datetime.datetime'>.strptime(ordinal_str2025-029, "%Y-%j").date()72print(f"\nParsed ordinal {ordinal_str2025-029}: {parsed_ordinal2025-01-29}")7374# Format codes reference75print("\nCommon format codes:")76print("  %Y - 4-digit year (2025)")77print("  %m - 2-digit month (01-12)")78print("  %d - 2-digit day (01-31)")79print("  %b - Short month (Jan)")80print("  %B - Full month (January)")81print("  %j - Day of year (001-366)")
    outputNone
    
    Parsed 2025/01/29: 2025-01-29
    Parsed January 29, 2025: 2025-01-29
    
    Parsed ordinal 2025-029: 2025-01-29
    
    Common format codes:
      %Y - 4-digit year (2025)
      %m - 2-digit month (01-12)
      %d - 2-digit day (01-31)
      %b - Short month (Jan)
      %B - Full month (January)
      %j - Day of year (001-366)
date_parsing Converting strings to date objects

Common Operations

  • Add/subtract days using timedelta
  • Compare dates
  • Get day of week
  • Calculate difference
  • Format to string

Immutability

Dates are immutable - operations return new instances.

Exercise: practical.py

Calculate ages, count days until events, and find business days