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.

Parsing Dates

create.py
# Create specific date

from datetime import date
import calendar

# Create specific dates
# Create with year, month, day
date1 = 
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()
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
import time
timestamp = time.time()
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 = 
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()
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
import time
timestamp = time.time()
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 = 
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()
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
import time
timestamp = time.time()
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()]})")

current.py
# Current date

from datetime import date
import calendar

# Get current date
# Current date
today = date.today()
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}")

components.py
# 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()]}")

compare.py
# 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()
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()}")

parse.py
# Parse date string

from datetime import date, datetime

# Parse date strings
# Parse ISO format (YYYY-MM-DD)
iso = 
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 = 
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 = 
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)")

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.

date_creation Creating date objects with date(), date.today(), and from timestamps
current_date Getting today's date and working with the system clock
date_components Accessing year, month, day, weekday, and calendar information
date_comparison Comparing dates and checking chronological order
date_parsing Converting strings to date objects

Exercise: practical.py

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