Date/Time Objects

UpComing SoftWare Training Demos

🚀 *Playwright With AI Testing Demo In Telugu*
🗓️ *Date:* 28 Oct2026, 08:00 PM IST
📝 *Register Now!:*
https://www.vlrt.in/3r
👥 *Join WA Community:*
https://www.vlrt.in/3w
💡 *Course Content:*
https://www.vlrt.in/3c
▶️ *Demo Videos:*
https://www.vlrt.in/3v

🚀 *Gen AI Engineer (Production Focused)*
🗓️ *Date:* 29th Oct 2026, 06:00PM IST
📝 *Register Now!:*
https://www.vlrt.in/gr
👥 *Join WA Community:*
https://www.vlrt.in/gw
💡*Course Content:*
https://www.vlrt.in/ai
▶️ *Demo Videos:*
https://www.vlrt.in/gv

🚀 *Vulnerability Management Training Demo*
🗓️ *Date:* 28th Oct 2026, 10:00 AM IST
📝*Register Now!:*
https://www.vlrt.in/vr
👥 *Join Community:*
https://www.vlrt.in/cw
💡 *Course Content:*
https://www.vlrt.in/vc
▶️ *Demo Videos:*
https://www.vlrt.in/Vm

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 import: from 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

  • Else Block in Exception Handling in Python

    Else Block in Exception Handling in Python The else block in Python exception handling executes only if the try block completes successfully without any exceptions. It’s placed after all except blocks and before the finally block. Basic Syntax: python try: # Code that might raise an exception except SomeException: # Handle the exception else: # Code that runs only if no exception…

  • append(), extend(), and insert() methods in Python lists

    append(), extend(), and insert() methods in Python lists, along with slicing where applicable. 1. append() Method Adds a single element to the end of the list. Examples: 2. extend() Method Adds multiple elements (iterable items) to the end of the list. Examples: 3. insert() Method Inserts an element at a specific position. Examples: Key Differences: Method Modifies List? Adds Single/Multiple Elements? Position append() ✅ Yes Single element (even if it’s a list) End…

  • String Validation Methods

    Complete List of Python String Validation Methods Python provides several built-in string methods to check if a string meets certain criteria. These methods return True or False and are useful for input validation, data cleaning, and text processing. 1. Case Checking Methods Method Description Example isupper() Checks if all characters are uppercase “HELLO”.isupper() → True islower() Checks if all…

  • Dictionaries

    Python Dictionaries: Explanation with Examples A dictionary in Python is an unordered collection of items that stores data in key-value pairs. Dictionaries are: Creating a Dictionary python # Empty dictionary my_dict = {} # Dictionary with initial values student = { “name”: “John Doe”, “age”: 21, “courses”: [“Math”, “Physics”, “Chemistry”], “GPA”: 3.7 } Accessing Dictionary Elements…

  • Why Python is So Popular: Key Reasons Behind Its Global Fame

    Python’s fame and widespread adoption across various sectors can be attributed to its unique combination of simplicity, versatility, and a robust ecosystem. Here are the key reasons why Python is so popular and widely used in different industries: 1. Easy to Learn and Use 2. Versatility Python supports multiple programming paradigms, including: This versatility allows…

  • Sets in Python

    Sets in Python A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add or remove items, but the elements themselves must be immutable (like numbers, strings, or tuples). Key Characteristics of Sets: Different Ways to Create Sets in Python Here are various methods to create sets in…

Leave a Reply

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