Date/Time Objects

Creating and Manipulating Date/Time Objects in Python

1. Creating Date and Time Objects

Creating Date Objects

python

from datetime import date, time, datetime

# Create date objects
date1 = date(2023, 12, 25)  # Christmas 2023
date2 = date(2024, 1, 1)    # New Year 2024
date3 = date(2023, 6, 15)   # Random date

print("Date Objects:")
print(f"Christmas: {date1}")
print(f"New Year: {date2}")
print(f"Random date: {date3}")

Creating Time Objects

python

# Create time objects
time1 = time(14, 30, 45)        # 2:30:45 PM
time2 = time(9, 0, 0)           # 9:00:00 AM
time3 = time(23, 45, 30, 500000) # 11:45:30.500000 PM

print("\nTime Objects:")
print(f"Time 1: {time1}")
print(f"Time 2: {time2}")
print(f"Time 3: {time3}")

Creating DateTime Objects

python

# Create datetime objects
dt1 = datetime(2023, 12, 25, 14, 30, 45)  # Christmas afternoon
dt2 = datetime(2024, 1, 1, 0, 0, 0)       # New Year midnight
dt3 = datetime(2023, 6, 15, 9, 15, 30)    # Random datetime

print("\nDateTime Objects:")
print(f"Christmas: {dt1}")
print(f"New Year: {dt2}")
print(f"Random: {dt3}")

2. Using combine() Method

Combine Date and Time

python

from datetime import date, time, datetime

# Create separate date and time
my_date = date(2023, 12, 25)
my_time = time(18, 30, 0)  # 6:30 PM

# Combine them into datetime
combined_dt = datetime.combine(my_date, my_time)
print(f"Combined DateTime: {combined_dt}")
# Output: 2023-12-25 18:30:00

# Multiple combinations
dates = [date(2023, 12, 25), date(2024, 1, 1), date(2024, 2, 14)]
times = [time(9, 0, 0), time(14, 30, 0), time(19, 0, 0)]

for d, t in zip(dates, times):
    combined = datetime.combine(d, t)
    print(f"{d} at {t} -> {combined}")

3. Comparing Objects

Date Comparisons

python

from datetime import date

# Create dates
today = date(2023, 12, 25)
tomorrow = date(2023, 12, 26)
yesterday = date(2023, 12, 24)

print("Date Comparisons:")
print(f"today > yesterday: {today > yesterday}")  # True
print(f"today < tomorrow: {today < tomorrow}")    # True
print(f"today == yesterday: {today == yesterday}") # False

# Check if date is in range
start_date = date(2023, 12, 1)
end_date = date(2023, 12, 31)
print(f"Is today in December 2023? {start_date <= today <= end_date}")  # True

DateTime Comparisons

python

from datetime import datetime

# Create datetimes
meeting1 = datetime(2023, 12, 25, 10, 0, 0)
meeting2 = datetime(2023, 12, 25, 14, 0, 0)
meeting3 = datetime(2023, 12, 26, 10, 0, 0)

print("\nDateTime Comparisons:")
print(f"Meeting1 before Meeting2: {meeting1 < meeting2}")  # True
print(f"Meeting2 after Meeting3: {meeting2 > meeting3}")   # False
print(f"Same day different times: {meeting1.date() == meeting2.date()}")  # True

4. Adding and Subtracting Objects

Using timedelta for Arithmetic

python

from datetime import datetime, timedelta

current_dt = datetime(2023, 12, 25, 10, 0, 0)
print(f"Current: {current_dt}")

# Adding time
one_day_later = current_dt + timedelta(days=1)
three_hours_later = current_dt + timedelta(hours=3)
one_week_later = current_dt + timedelta(weeks=1)

print(f"One day later: {one_day_later}")
print(f"Three hours later: {three_hours_later}")
print(f"One week later: {one_week_later}")

# Subtracting time
one_day_ago = current_dt - timedelta(days=1)
two_hours_ago = current_dt - timedelta(hours=2)

print(f"One day ago: {one_day_ago}")
print(f"Two hours ago: {two_hours_ago}")

Complex Date Arithmetic

python

from datetime import datetime, timedelta

# Project timeline example
project_start = datetime(2023, 12, 25, 9, 0, 0)

# Add various time periods
design_end = project_start + timedelta(days=7)  # 1 week for design
development_end = design_end + timedelta(days=14)  # 2 weeks for development
testing_end = development_end + timedelta(days=7)  # 1 week for testing

print("Project Timeline:")
print(f"Start: {project_start}")
print(f"Design complete: {design_end}")
print(f"Development complete: {development_end}")
print(f"Testing complete: {testing_end}")

# Calculate total project duration
total_duration = testing_end - project_start
print(f"Total project duration: {total_duration.days} days")

5. Complete Example Programs

Program 1: Event Scheduler

python

from datetime import datetime, timedelta, date, time

class EventScheduler:
    def __init__(self):
        self.events = []
    
    def add_event(self, name, event_date, event_time, duration_hours=1):
        event_dt = datetime.combine(event_date, event_time)
        end_time = event_dt + timedelta(hours=duration_hours)
        
        self.events.append({
            'name': name,
            'start': event_dt,
            'end': end_time
        })
        print(f"Event '{name}' scheduled from {event_dt} to {end_time}")
    
    def list_events(self):
        print("\nScheduled Events:")
        for event in sorted(self.events, key=lambda x: x['start']):
            duration = event['end'] - event['start']
            print(f"- {event['name']}: {event['start']} to {event['end']} ({duration})")

# Usage
scheduler = EventScheduler()

# Schedule events
scheduler.add_event("Team Meeting", date(2023, 12, 26), time(10, 0, 0), 2)
scheduler.add_event("Lunch", date(2023, 12, 26), time(12, 30, 0), 1)
scheduler.add_event("Client Call", date(2023, 12, 27), time(14, 0, 0), 1.5)

scheduler.list_events()

Program 2: Date Calculator

python

from datetime import date, timedelta

class DateCalculator:
    @staticmethod
    def calculate_age(birth_date):
        today = date.today()
        age = today.year - birth_date.year
        
        # Check if birthday hasn't occurred this year yet
        if today.month < birth_date.month or (today.month == birth_date.month and today.day < birth_date.day):
            age -= 1
        
        return age
    
    @staticmethod
    def days_until(target_date):
        today = date.today()
        return (target_date - today).days
    
    @staticmethod
    def add_business_days(start_date, business_days):
        current_date = start_date
        added_days = 0
        
        while added_days < business_days:
            current_date += timedelta(days=1)
            # Skip weekends (0=Monday, 6=Sunday)
            if current_date.weekday() < 5:
                added_days += 1
        
        return current_date

# Usage
calculator = DateCalculator()

# Calculate age
birthday = date(1990, 6, 15)
age = calculator.calculate_age(birthday)
print(f"Age: {age} years")

# Days until New Year
new_year = date(2024, 1, 1)
days_left = calculator.days_until(new_year)
print(f"Days until New Year: {days_left}")

# Add business days
start = date(2023, 12, 25)  # Monday
deadline = calculator.add_business_days(start, 5)  # Add 5 business days
print(f"Start: {start}, Deadline: {deadline}")

Program 3: Time Difference Calculator

python

from datetime import datetime

class TimeDifferenceCalculator:
    @staticmethod
    def time_between(dt1, dt2):
        difference = abs(dt2 - dt1)
        
        days = difference.days
        seconds = difference.seconds
        hours = seconds // 3600
        minutes = (seconds % 3600) // 60
        seconds = seconds % 60
        
        return {
            'total_seconds': difference.total_seconds(),
            'days': days,
            'hours': hours,
            'minutes': minutes,
            'seconds': seconds
        }
    
    @staticmethod
    def format_difference(dt1, dt2):
        diff = TimeDifferenceCalculator.time_between(dt1, dt2)
        
        if dt1 < dt2:
            direction = "after"
        else:
            direction = "before"
        
        parts = []
        if diff['days'] > 0:
            parts.append(f"{diff['days']} days")
        if diff['hours'] > 0:
            parts.append(f"{diff['hours']} hours")
        if diff['minutes'] > 0:
            parts.append(f"{diff['minutes']} minutes")
        if diff['seconds'] > 0:
            parts.append(f"{diff['seconds']} seconds")
        
        time_str = ", ".join(parts)
        return f"{dt2} is {time_str} {direction} {dt1}"

# Usage
calculator = TimeDifferenceCalculator()

# Calculate differences
start_time = datetime(2023, 12, 25, 10, 0, 0)
end_time = datetime(2023, 12, 26, 14, 30, 45)

difference = calculator.time_between(start_time, end_time)
print("Time Difference:")
for unit, value in difference.items():
    print(f"{unit}: {value}")

formatted = calculator.format_difference(start_time, end_time)
print(f"\nFormatted: {formatted}")

Key Points to Remember:

  1. Creating Objects:
    • date(year, month, day)
    • time(hour, minute, second)
    • datetime(year, month, day, hour, minute, second)
  2. Combining: Use datetime.combine(date, time)
  3. Comparing: Use standard operators (<>==, etc.)
  4. Arithmetic: Use timedelta for adding/subtracting time
  5. Always importfrom datetime import date, time, datetime, timedelta

These examples show how powerful and flexible Python’s datetime module is for handling all kinds of date and time operations!

Similar Posts

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

  • Negative lookbehind assertion

    A negative lookbehind assertion in Python’s re module is a zero-width assertion that checks if a pattern is not present immediately before the current position. It is written as (?<!…). It’s the opposite of a positive lookbehind and allows you to exclude matches based on what precedes them. Similar to the positive lookbehind, the pattern…

  • The Fractions module

    The Fractions module in Python is a built-in module that provides support for rational number arithmetic. It allows you to work with fractions (like 1/2, 3/4, etc.) exactly, without the precision issues that can occur with floating-point numbers. What Problems Does It Solve? Problem with Floating-Point Numbers: python # Floating-point precision issue print(0.1 + 0.2) # Output:…

  • re.sub()

    Python re.sub() Method Explained The re.sub() method is used for searching and replacing text patterns in strings. It’s one of the most powerful regex methods for text processing. Syntax python re.sub(pattern, repl, string, count=0, flags=0) Example 1: Basic Text Replacement python import re text = “The color of the sky is blue. My favorite color is blue too.” #…

Leave a Reply

Your email address will not be published. Required fields are marked *