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

  • positive lookbehind assertion

    A positive lookbehind assertion in Python’s re module is a zero-width assertion that checks if the pattern that precedes it is present, without including that pattern in the overall match. It’s the opposite of a lookahead. It is written as (?<=…). The key constraint for lookbehind assertions in Python is that the pattern inside the…

  • pop(), remove(), clear(), and del 

    pop(), remove(), clear(), and del with 5 examples each, including slicing where applicable: 1. pop([index]) Removes and returns the item at the given index. If no index is given, it removes the last item. Examples: 2. remove(x) Removes the first occurrence of the specified value x. Raises ValueError if not found. Examples: 3. clear() Removes all elements from the list, making it empty. Examples: 4. del Statement Deletes elements by index or slice (not a method, but a…

  • file properties and methods

    1. file.closed – Is the file door shut? Think of a file like a door. file.closed tells you if the door is open or closed. python # Open the file (open the door) f = open(“test.txt”, “w”) f.write(“Hello!”) print(f.closed) # Output: False (door is open) # Close the file (close the door) f.close() print(f.closed) # Output: True (door is…

  • Keyword-Only Arguments in Python and mixed

    Keyword-Only Arguments in Python Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments. Syntax Use the * symbol in the function definition to indicate that all parameters after it are keyword-only: python def function_name(param1, param2, *, keyword_only1, keyword_only2): # function body Simple Examples Example 1: Basic Keyword-Only Arguments…

  • 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…

  • date time modules class55

    In Python, the primary modules for handling dates and times are: 🕰️ Key Built-in Modules 1. datetime This is the most essential module. It provides classes for manipulating dates and times in both simple and complex ways. Class Description Example Usage date A date (year, month, day). date.today() time A time (hour, minute, second, microsecond,…

Leave a Reply

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