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

  • ASCII ,Uni Code Related Functions in Python

    ASCII Code and Related Functions in Python ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns numerical values to letters, digits, punctuation marks, and other characters. Here’s an explanation of ASCII and Python functions that work with it. ASCII Basics Python Functions for ASCII 1. ord() – Get ASCII value of a…

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

  • Create lists

    In Python, there are multiple ways to create lists, depending on the use case. Below are the most common methods: 1. Direct Initialization (Using Square Brackets []) The simplest way to create a list is by enclosing elements in square brackets []. Example: python empty_list = [] numbers = [1, 2, 3, 4] mixed_list = [1, “hello”, 3.14,…

  • The print() Function in Python

    The print() Function in Python: Complete Guide The print() function is Python’s built-in function for outputting data to the standard output (usually the console). Let’s explore all its arguments and capabilities in detail. Basic Syntax python print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Arguments Explained 1. *objects (Positional Arguments) The values to print. You can pass multiple items separated by commas. Examples:…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

Leave a Reply

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