📅 Working with Dates

Working with dates and times is essential for most real-world applications. Python's datetime module provides powerful tools for creating, manipulating, and formatting dates and times, enabling you to build time-aware applications with scheduling, logging, and data analysis capabilities.

Think of Python's datetime functionality as a comprehensive calendar and clock system - you can represent any moment in time, calculate durations, format dates for display, and perform complex time-based calculations with ease.

import datetime

# Creating and working with dates
today = datetime.date.today()
print(f"Today is: {today}")

# Create a specific date
birthday = datetime.date(1990, 5, 15)
print(f"Birthday: {birthday}")

# Calculate age in days
age_in_days = today - birthday
print(f"Age in days: {age_in_days.days}")

# Working with times
now = datetime.datetime.now()
print(f"Current time: {now}")

# Format dates for display
formatted = now.strftime("%B %d, %Y at %I:%M %p")
print(f"Formatted: {formatted}")

🎯 Understanding Python's Date and Time Objects

Python provides several types of date and time objects, each designed for specific use cases and levels of precision.

Creating Date Objects

Date objects represent calendar dates without time information, perfect for events, deadlines, and date-based calculations.

import datetime

# Different ways to create dates
today = datetime.date.today()
print(f"Today: {today}")

# Create specific dates
new_year = datetime.date(2024, 1, 1)
independence_day = datetime.date(2024, 7, 4)

print(f"New Year: {new_year}")
print(f"Independence Day: {independence_day}")

# Access date components
print(f"Year: {today.year}")
print(f"Month: {today.month}")
print(f"Day: {today.day}")
print(f"Weekday: {today.weekday()}")  # 0=Monday, 6=Sunday

# Create dates from strings
date_string = "2024-12-25"
christmas = datetime.datetime.strptime(date_string, "%Y-%m-%d").date()
print(f"Christmas: {christmas}")

Working with Time Objects

Time objects represent time of day without date information, useful for schedules and recurring events.

import datetime

# Create time objects
morning_meeting = datetime.time(9, 30, 0)  # 9:30 AM
lunch_time = datetime.time(12, 0)          # 12:00 PM
evening_deadline = datetime.time(17, 30)   # 5:30 PM

print(f"Morning meeting: {morning_meeting}")
print(f"Lunch time: {lunch_time}")
print(f"Evening deadline: {evening_deadline}")

# Access time components
print(f"Hour: {morning_meeting.hour}")
print(f"Minute: {morning_meeting.minute}")
print(f"Second: {morning_meeting.second}")

# Current time
now_time = datetime.datetime.now().time()
print(f"Current time: {now_time}")

# Check if current time is after deadline
current_hour = datetime.datetime.now().hour
if current_hour > evening_deadline.hour:
    print("Past deadline!")
else:
    print("Still time to work")

DateTime Objects for Complete Timestamps

DateTime objects combine date and time, providing complete timestamp functionality for logging, scheduling, and precise time tracking.

import datetime

# Create datetime objects
now = datetime.datetime.now()
print(f"Current timestamp: {now}")

# Create specific datetime
project_deadline = datetime.datetime(2024, 6, 15, 23, 59, 59)
print(f"Project deadline: {project_deadline}")

# From date and time components
meeting_date = datetime.date(2024, 3, 20)
meeting_time = datetime.time(14, 30)
meeting_datetime = datetime.datetime.combine(meeting_date, meeting_time)
print(f"Meeting: {meeting_datetime}")

# Access all components
print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}")
print(f"Hour: {now.hour}, Minute: {now.minute}, Second: {now.second}")

# Create from timestamp
timestamp = 1640995200  # Unix timestamp
from_timestamp = datetime.datetime.fromtimestamp(timestamp)
print(f"From timestamp: {from_timestamp}")

⚡ Date and Time Calculations

Python makes it easy to perform calculations with dates and times using timedelta objects and arithmetic operations.

TimeDelta for Duration Calculations

TimeDelta objects represent durations and enable powerful date arithmetic for scheduling and planning applications.

import datetime

# Create timedelta objects
one_week = datetime.timedelta(weeks=1)
three_days = datetime.timedelta(days=3)
two_hours = datetime.timedelta(hours=2)
thirty_minutes = datetime.timedelta(minutes=30)

print(f"One week: {one_week}")
print(f"Three days: {three_days}")
print(f"Two hours: {two_hours}")

# Date arithmetic
today = datetime.date.today()
next_week = today + one_week
last_month = today - datetime.timedelta(days=30)

print(f"Today: {today}")
print(f"Next week: {next_week}")
print(f"Last month: {last_month}")

# Calculate differences
start_date = datetime.date(2024, 1, 1)
end_date = datetime.date(2024, 12, 31)
duration = end_date - start_date

print(f"Days in year: {duration.days}")
print(f"Weeks in year: {duration.days // 7}")

# Complex calculations
project_start = datetime.datetime(2024, 3, 1, 9, 0)
work_days = 5 * 8  # 5 days × 8 hours
project_hours = datetime.timedelta(hours=work_days)
project_end = project_start + project_hours

print(f"Project start: {project_start}")
print(f"Project end: {project_end}")

Business Date Calculations

Real-world applications often need to calculate business days, handle holidays, and work with recurring schedules.

import datetime

def add_business_days(start_date, business_days):
    """Add business days (excluding weekends) to a date"""
    current_date = start_date
    days_added = 0
    
    while days_added < business_days:
        current_date += datetime.timedelta(days=1)
        # Monday = 0, Sunday = 6
        if current_date.weekday() < 5:  # Monday through Friday
            days_added += 1
    
    return current_date

def calculate_age(birth_date, current_date=None):
    """Calculate age in years, months, and days"""
    if current_date is None:
        current_date = datetime.date.today()
    
    years = current_date.year - birth_date.year
    months = current_date.month - birth_date.month
    days = current_date.day - birth_date.day
    
    # Adjust for negative days
    if days < 0:
        months -= 1
        # Get days in previous month
        if current_date.month == 1:
            prev_month_last = datetime.date(current_date.year - 1, 12, 31)
        else:
            prev_month_last = datetime.date(current_date.year, current_date.month - 1, 1) + datetime.timedelta(days=31)
            prev_month_last = prev_month_last.replace(day=1) - datetime.timedelta(days=1)
        days += prev_month_last.day
    
    # Adjust for negative months
    if months < 0:
        years -= 1
        months += 12
    
    return {"years": years, "months": months, "days": days}

# Business calculations
start = datetime.date(2024, 1, 15)  # Monday
business_deadline = add_business_days(start, 10)
print(f"10 business days from {start}: {business_deadline}")

# Age calculation
birth = datetime.date(1990, 5, 15)
age = calculate_age(birth)
print(f"Age: {age['years']} years, {age['months']} months, {age['days']} days")

🚀 Date Formatting and Parsing

Converting between dates and strings is crucial for user interfaces, file processing, and data exchange.

Formatting Dates for Display

Use strftime() to convert date objects to formatted strings for user-friendly display.

import datetime

now = datetime.datetime.now()
birthday = datetime.date(1990, 5, 15)

# Common format patterns
formats = {
    "ISO Format": now.strftime("%Y-%m-%d %H:%M:%S"),
    "US Format": now.strftime("%m/%d/%Y %I:%M %p"),
    "European Format": now.strftime("%d/%m/%Y %H:%M"),
    "Long Format": now.strftime("%A, %B %d, %Y"),
    "Short Format": now.strftime("%a, %b %d"),
    "Time Only": now.strftime("%H:%M:%S"),
    "Date Only": birthday.strftime("%B %d, %Y")
}

print("Date Formatting Examples:")
for name, formatted in formats.items():
    print(f"{name:15}: {formatted}")

# Custom business formats
invoice_date = now.strftime("Invoice Date: %B %d, %Y")
log_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S]")
filename_date = now.strftime("report_%Y%m%d_%H%M%S.txt")

print(f"\n{invoice_date}")
print(f"{log_timestamp} System started")
print(f"Filename: {filename_date}")

Parsing Dates from Strings

Use strptime() to convert string representations back to date objects for processing.

import datetime

# Common date string formats
date_strings = [
    ("2024-03-15", "%Y-%m-%d"),
    ("03/15/2024", "%m/%d/%Y"),
    ("15/03/2024", "%d/%m/%Y"),
    ("March 15, 2024", "%B %d, %Y"),
    ("15-Mar-2024", "%d-%b-%Y"),
    ("2024-03-15 14:30:00", "%Y-%m-%d %H:%M:%S"),
    ("03/15/24 2:30 PM", "%m/%d/%y %I:%M %p")
]

print("Parsing Date Strings:")
for date_str, format_str in date_strings:
    try:
        parsed = datetime.datetime.strptime(date_str, format_str)
        print(f"'{date_str}' -> {parsed}")
    except ValueError as e:
        print(f"'{date_str}' -> Error: {e}")

# Flexible parsing function
def parse_date_flexible(date_string):
    """Try multiple common formats to parse a date string"""
    formats = [
        "%Y-%m-%d", "%m/%d/%Y", "%d/%m/%Y", 
        "%Y-%m-%d %H:%M:%S", "%m/%d/%Y %I:%M %p",
        "%B %d, %Y", "%d-%b-%Y"
    ]
    
    for fmt in formats:
        try:
            return datetime.datetime.strptime(date_string, fmt)
        except ValueError:
            continue
    
    raise ValueError(f"Unable to parse date: {date_string}")

# Test flexible parsing
test_dates = ["2024-03-15", "03/15/2024", "March 15, 2024"]
for test_date in test_dates:
    try:
        result = parse_date_flexible(test_date)
        print(f"Flexible parse '{test_date}': {result.date()}")
    except ValueError as e:
        print(f"Error: {e}")

Hands-on Exercise

Create a simple birthday calculator that tells you how many days until your next birthday and how old you will be. Use datetime to calculate the difference between today and your birthday.

python
import datetime

def calculate_birthday_info(birth_year, birth_month, birth_day):
    # TODO: Get today's date
    # TODO: Create your birth date
    # TODO: Create this year's birthday
    # TODO: If birthday already passed this year, use next year
    # TODO: Calculate days until birthday
    # TODO: Calculate age on next birthday
    # TODO: Return the information
    pass

# TODO: Test with your birthday
birth_year = 1990
birth_month = 6
birth_day = 15

result = calculate_birthday_info(birth_year, birth_month, birth_day)
print(f"Days until birthday: {result['days_until']}")
print(f"Age on next birthday: {result['age_on_birthday']}")
print(f"Next birthday: {result['next_birthday']}")

Solution and Explanation 💡

Click to see the complete solution
import datetime

def calculate_birthday_info(birth_year, birth_month, birth_day):
    # Get today's date
    today = datetime.date.today()
    
    # Create your birth date
    birth_date = datetime.date(birth_year, birth_month, birth_day)
    
    # Create this year's birthday
    this_year_birthday = datetime.date(today.year, birth_month, birth_day)
    
    # If birthday already passed this year, use next year
    if this_year_birthday < today:
        next_birthday = datetime.date(today.year + 1, birth_month, birth_day)
    else:
        next_birthday = this_year_birthday
    
    # Calculate days until birthday
    days_until = (next_birthday - today).days
    
    # Calculate age on next birthday
    age_on_birthday = next_birthday.year - birth_year
    
    # Return the information
    return {
        'days_until': days_until,
        'age_on_birthday': age_on_birthday,
        'next_birthday': next_birthday.strftime("%B %d, %Y")
    }

# Test with your birthday
birth_year = 1990
birth_month = 6
birth_day = 15

result = calculate_birthday_info(birth_year, birth_month, birth_day)
print(f"Days until birthday: {result['days_until']}")
print(f"Age on next birthday: {result['age_on_birthday']}")
print(f"Next birthday: {result['next_birthday']}")

Key Learning Points:

  • 📌 datetime.date.today(): Gets current date without time information
  • 📌 datetime.date(): Creates specific dates with year, month, day
  • 📌 Date arithmetic: Subtract dates to get timedelta objects
  • 📌 Date comparison: Use <, >, == to compare dates
  • 📌 strftime(): Format dates as readable strings

Learn more about mathematical operations to perform calculations with your date-based data.

Essential Date Methods and Functions

Understanding the most commonly used date methods helps you work efficiently with temporal data.

Method/FunctionPurposeExampleResult
date.today()Get current datedatetime.date.today()2024-03-15
datetime.now()Get current datetimedatetime.datetime.now()2024-03-15 14:30:25
strftime()Format date as stringdate.strftime("%B %d, %Y")"March 15, 2024"
strptime()Parse string to datedatetime.strptime("2024-03-15", "%Y-%m-%d")datetime object
isoformat()ISO 8601 formatdate.isoformat()"2024-03-15"
weekday()Day of week (0=Mon)date.weekday()4 (Friday)
replace()Create new date with changesdate.replace(year=2025)Modified date
timedelta()Create durationtimedelta(days=7)7-day duration

Test Your Knowledge

Test what you've learned about working with dates:

What's Next?

Now that you can handle dates and times effectively, you're ready to explore mathematical operations. Learn how to perform complex calculations, statistical analysis, and scientific computing to complement your date handling skills.

Ready to continue? Check out our lesson on Mathematical Operations.

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent