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

  • Python Installation Guide: Easy Steps for Windows, macOS, and Linux

    Installing Python is a straightforward process, and it can be done on various operating systems like Windows, macOS, and Linux. Below are step-by-step instructions for installing Python on each platform. 1. Installing Python on Windows Step 1: Download Python Step 2: Run the Installer Step 3: Verify Installation If Python is installed correctly, it will…

  • Type Conversion Functions

    Type Conversion Functions in Python 🔄 Type conversion (or type casting) transforms data from one type to another. Python provides built-in functions for these conversions. Here’s a comprehensive guide with examples: 1. int(x) 🔢 Converts x to an integer. Python 2. float(x) afloat Converts x to a floating-point number. Python 3. str(x) 💬 Converts x…

  • Static Methods

    The primary use of a static method in Python classes is to define a function that logically belongs to the class but doesn’t need access to the instance’s data (like self) or the class’s state (like cls). They are essentially regular functions that are grouped within a class namespace. Key Characteristics and Use Cases General…

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

  • Functions Returning Functions

    Understanding Functions Returning Functions In Python, functions can return other functions, which is a powerful feature of functional programming. Basic Example python def outer(): def inner(): print(“Welcome!”) return inner # Return the inner function (without calling it) # Calling outer() returns the inner function f = outer() # f now refers to the inner function…

  • Password Strength Checker

    python Enhanced Password Strength Checker python import re def is_strong(password): “”” Check if a password is strong based on multiple criteria. Returns (is_valid, message) tuple. “”” # Define criteria and error messages criteria = [ { ‘check’: len(password) >= 8, ‘message’: “at least 8 characters” }, { ‘check’: bool(re.search(r'[A-Z]’, password)), ‘message’: “one uppercase letter (A-Z)”…

Leave a Reply

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