Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Datetime Module

Python Datetime Module - Complete Guide

Work with dates and times easily in Python.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What is Datetime Module?
  • Working with Dates
  • Working with Time
  • Working with Datetime
  • Date Arithmetic
  • Formatting Dates and Times
  • Real-World Example
  • Best Practices
  • Try It Yourself
  • Quick Quiz
  • Frequently Asked Questions
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • What is datetime module — working with dates and times
  • date — working with dates (year, month, day)
  • time — working with times (hour, minute, second)
  • datetime — combining date and time
  • timedelta — date arithmetic (adding, subtracting)
  • Formatting — converting dates to strings and back

What is Datetime Module?

The datetime module is Python's built-in toolkit for working with dates and times. It lets you create, manipulate, and format dates and times easily.

Think of datetime like a calendar and clock combined. You can ask it "What's today's date?", "What time is it?", "What was the date 10 days ago?", or "What will the date be in 30 days?"

💡 Key concept: The datetime module gives you everything you need to work with dates and times in Python.

Working with Dates

1

Creating and Using Dates

The date class handles dates without time. It stores year, month, and day.

# Working with Dates

from datetime import date

print("=" * 50)
print("WORKING WITH DATES")
print("=" * 50)

# ============================================================
# CREATING DATES
# ============================================================

print("\n1. CREATING DATES")

# Today's date
today = date.today()
print(f"   Today: {today}")

# Create a specific date
my_birthday = date(1990, 5, 15)
print(f"   My birthday: {my_birthday}")

# Create from year, month, day
new_year = date(2024, 1, 1)
print(f"   New Year 2024: {new_year}")


# ============================================================
# DATE PROPERTIES
# ============================================================

print("\n2. DATE PROPERTIES")

d = date(2024, 12, 25)

print(f"   Date: {d}")
print(f"   Year: {d.year}")
print(f"   Month: {d.month}")
print(f"   Day: {d.day}")
print(f"   Weekday (Monday=0): {d.weekday()}")
print(f"   Weekday name: {d.strftime('%A')}")
print(f"   ISO weekday (Monday=1): {d.isoweekday()}")


# ============================================================
# COMPARING DATES
# ============================================================

print("\n3. COMPARING DATES")

date1 = date(2024, 1, 1)
date2 = date(2024, 12, 31)
date3 = date(2024, 6, 15)

print(f"   date1: {date1}")
print(f"   date2: {date2}")
print(f"   date3: {date3}")
print(f"   date1 < date2: {date1 < date2}")
print(f"   date1 > date3: {date1 > date3}")
print(f"   date1 == date3: {date1 == date3}")
print(f"   date1 != date2: {date1 != date2}")


# ============================================================
# DATE FROM STRING
# ============================================================

print("\n4. DATE FROM STRING")

from datetime import datetime

# Parse a date from string
date_str = "2024-03-15"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d").date()
print(f"   String: {date_str}")
print(f"   Parsed: {parsed_date}")


# ============================================================
# ISO FORMAT
# ============================================================

print("\n5. ISO FORMAT")

d = date(2024, 7, 4)
print(f"   Date: {d}")
print(f"   ISO format: {d.isoformat()}")

Date key points:

  • date(year, month, day) — create a date
  • date.today() — get today's date
  • Properties — year, month, day, weekday
  • Compare — use <, >, ==

Quick Check: How do you get today's date? (Answer: date.today())

Working with Time

2

Creating and Using Times

The time class handles times without dates. It stores hour, minute, second, and microsecond.

# Working with Time

from datetime import time

print("=" * 50)
print("WORKING WITH TIME")
print("=" * 50)

# ============================================================
# CREATING TIMES
# ============================================================

print("\n1. CREATING TIMES")

# Create a specific time
morning = time(9, 30, 0)
print(f"   Morning: {morning}")

# With seconds and microseconds
noon = time(12, 0, 15, 500000)
print(f"   Noon: {noon}")

# Only hour and minute
evening = time(18, 30)
print(f"   Evening: {evening}")

# Current time (with datetime)
from datetime import datetime
current_time = datetime.now().time()
print(f"   Current time: {current_time}")


# ============================================================
# TIME PROPERTIES
# ============================================================

print("\n2. TIME PROPERTIES")

t = time(14, 30, 45, 123456)

print(f"   Time: {t}")
print(f"   Hour: {t.hour}")
print(f"   Minute: {t.minute}")
print(f"   Second: {t.second}")
print(f"   Microsecond: {t.microsecond}")


# ============================================================
# COMPARING TIMES
# ============================================================

print("\n3. COMPARING TIMES")

t1 = time(8, 0, 0)
t2 = time(12, 0, 0)
t3 = time(8, 0, 0)

print(f"   t1: {t1}")
print(f"   t2: {t2}")
print(f"   t1 < t2: {t1 < t2}")
print(f"   t1 == t3: {t1 == t3}")
print(f"   t1 != t2: {t1 != t2}")


# ============================================================
# ISO FORMAT
# ============================================================

print("\n4. ISO FORMAT")

t = time(14, 30, 45)
print(f"   Time: {t}")
print(f"   ISO format: {t.isoformat()}")

Time key points:

  • time(hour, minute, second) — create a time
  • Properties — hour, minute, second, microsecond
  • Current time — datetime.now().time()
  • Compare — use <, >, ==

Quick Check: How do you get the current time? (Answer: datetime.now().time())

Working with Datetime

3

Combining Date and Time

The datetime class combines both date and time. It's the most commonly used class.

# Working with Datetime

from datetime import datetime

print("=" * 50)
print("WORKING WITH DATETIME")
print("=" * 50)

# ============================================================
# CREATING DATETIME
# ============================================================

print("\n1. CREATING DATETIME")

# Now
now = datetime.now()
print(f"   Now: {now}")

# Create a specific datetime
meeting = datetime(2024, 6, 15, 10, 30, 0)
print(f"   Meeting: {meeting}")

# Current date and time (combine date and time)
from datetime import date, time
today = date.today()
current_time = time(14, 30)
combined = datetime.combine(today, current_time)
print(f"   Combined: {combined}")


# ============================================================
# DATETIME PROPERTIES
# ============================================================

print("\n2. DATETIME PROPERTIES")

dt = datetime(2024, 12, 25, 14, 30, 45, 123456)

print(f"   Datetime: {dt}")
print(f"   Year: {dt.year}")
print(f"   Month: {dt.month}")
print(f"   Day: {dt.day}")
print(f"   Hour: {dt.hour}")
print(f"   Minute: {dt.minute}")
print(f"   Second: {dt.second}")
print(f"   Microsecond: {dt.microsecond}")
print(f"   Weekday: {dt.weekday()}")


# ============================================================
# EXTRACTING DATE AND TIME
# ============================================================

print("\n3. EXTRACTING DATE AND TIME")

dt = datetime.now()

# Extract date
only_date = dt.date()
print(f"   Only date: {only_date}")

# Extract time
only_time = dt.time()
print(f"   Only time: {only_time}")


# ============================================================
# COMPARING DATETIME
# ============================================================

print("\n4. COMPARING DATETIME")

dt1 = datetime(2024, 1, 1, 0, 0, 0)
dt2 = datetime(2024, 12, 31, 23, 59, 59)

print(f"   dt1: {dt1}")
print(f"   dt2: {dt2}")
print(f"   dt1 < dt2: {dt1 < dt2}")


# ============================================================
# PARSING DATETIME FROM STRING
# ============================================================

print("\n5. PARSING DATETIME FROM STRING")

# Parse from string
date_str = "2024-03-15 14:30:45"
parsed = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(f"   String: {date_str}")
print(f"   Parsed: {parsed}")


# ============================================================
# ISO FORMAT
# ============================================================

print("\n6. ISO FORMAT")

dt = datetime.now()
print(f"   Datetime: {dt}")
print(f"   ISO format: {dt.isoformat()}")

Datetime key points:

  • datetime.now() — current date and time
  • datetime(year, month, day, hour, minute, second) — create
  • Properties — all date and time properties
  • date() — extract date
  • time() — extract time

Quick Check: How do you get the current date and time? (Answer: datetime.now())

Date Arithmetic

4

Adding and Subtracting Dates

timedelta represents a duration of time. You can add or subtract it from dates and datetimes.

# Date Arithmetic with timedelta

from datetime import datetime, date, timedelta

print("=" * 50)
print("DATE ARITHMETIC")
print("=" * 50)

# ============================================================
# CREATING TIMEDELTA
# ============================================================

print("\n1. CREATING TIMEDELTA")

# Different ways to create timedelta
day = timedelta(days=1)
week = timedelta(weeks=1)
hour = timedelta(hours=1)
minute = timedelta(minutes=1)
second = timedelta(seconds=1)

print(f"   Day: {day}")
print(f"   Week: {week}")
print(f"   Hour: {hour}")
print(f"   Minute: {minute}")
print(f"   Second: {second}")

# Multiple units
two_weeks_three_days = timedelta(weeks=2, days=3)
print(f"   2 weeks and 3 days: {two_weeks_three_days}")


# ============================================================
# ADDING AND SUBTRACTING
# ============================================================

print("\n2. ADDING AND SUBTRACTING")

today = date.today()
print(f"   Today: {today}")

# Add days
tomorrow = today + timedelta(days=1)
print(f"   Tomorrow: {tomorrow}")

# Subtract days
yesterday = today - timedelta(days=1)
print(f"   Yesterday: {yesterday}")

# Add weeks
next_week = today + timedelta(weeks=1)
print(f"   Next week: {next_week}")

# Add multiple units
one_month = today + timedelta(days=30)
print(f"   ~One month: {one_month}")


# ============================================================
# TIMEDELTA WITH DATETIME
# ============================================================

print("\n3. TIMEDELTA WITH DATETIME")

now = datetime.now()
print(f"   Now: {now}")

# Add hours
later = now + timedelta(hours=2)
print(f"   +2 hours: {later}")

# Subtract minutes
earlier = now - timedelta(minutes=30)
print(f"   -30 minutes: {earlier}")

# Add seconds
future = now + timedelta(seconds=45)
print(f"   +45 seconds: {future}")


# ============================================================
# DIFFERENCE BETWEEN DATES
# ============================================================

print("\n4. DIFFERENCE BETWEEN DATES")

start = date(2024, 1, 1)
end = date(2024, 12, 31)

diff = end - start
print(f"   Start: {start}")
print(f"   End: {end}")
print(f"   Difference: {diff}")
print(f"   Days: {diff.days}")
print(f"   Seconds: {diff.total_seconds()}")


# ============================================================
# DIFFERENCE BETWEEN DATETIMES
# ============================================================

print("\n5. DIFFERENCE BETWEEN DATETIMES")

dt1 = datetime(2024, 1, 1, 0, 0, 0)
dt2 = datetime(2024, 1, 2, 12, 30, 0)

diff = dt2 - dt1
print(f"   dt1: {dt1}")
print(f"   dt2: {dt2}")
print(f"   Difference: {diff}")
print(f"   Days: {diff.days}")
print(f"   Seconds: {diff.seconds}")
print(f"   Total seconds: {diff.total_seconds()}")


# ============================================================
# COMMON TIMEDELTA OPERATIONS
# ============================================================

print("\n6. COMMON TIMEDELTA OPERATIONS")

now = datetime.now()

# Find the date 7 days ago
week_ago = now - timedelta(days=7)
print(f"   7 days ago: {week_ago}")

# Find the date 30 days from now
month_from_now = now + timedelta(days=30)
print(f"   30 days from now: {month_from_now}")

# Find the date 365 days from now
year_from_now = now + timedelta(days=365)
print(f"   365 days from now: {year_from_now}")

print(f"   Is year_from_now > now? {year_from_now > now}")

timedelta key points:

  • timedelta(days=, hours=, minutes=, seconds=) — create a duration
  • Add and subtract — from dates and datetimes
  • Difference — subtract two dates/datetimes
  • Properties — days, seconds, total_seconds()

Quick Check: How do you add 7 days to a date? (Answer: date + timedelta(days=7))

Formatting Dates and Times

5

Converting Dates to Strings and Back

strftime converts dates to strings. strptime converts strings to dates.

# Formatting Dates and Times

from datetime import datetime

print("=" * 50)
print("FORMATTING DATES AND TIMES")
print("=" * 50)

# ============================================================
# STRFTIME - Date to String
# ============================================================

print("\n1. STRFTIME - Date to String")

now = datetime.now()
print(f"   Now: {now}")

# Different formats
print(f"   Default: {now}")
print(f"   YYYY-MM-DD: {now.strftime('%Y-%m-%d')}")
print(f"   MM/DD/YYYY: {now.strftime('%m/%d/%Y')}")
print(f"   DD-MM-YYYY: {now.strftime('%d-%m-%Y')}")
print(f"   Full date: {now.strftime('%A, %B %d, %Y')}")
print(f"   Time 12hr: {now.strftime('%I:%M:%S %p')}")
print(f"   Time 24hr: {now.strftime('%H:%M:%S')}")
print(f"   Short date: {now.strftime('%b %d, %Y')}")
print(f"   Full datetime: {now.strftime('%A, %B %d, %Y at %I:%M %p')}")


# ============================================================
# COMMON FORMAT CODES
# ============================================================

print("\n2. COMMON FORMAT CODES")

print("""
┌─────────────┬────────────────────────────────────────────┐
│ Code        │ Meaning                                   │
├─────────────┼────────────────────────────────────────────┤
│ %Y          │ Year with century (2024)                  │
│ %y          │ Year without century (24)                 │
│ %m          │ Month as number (01-12)                   │
│ %B          │ Full month name (January)                 │
│ %b          │ Short month name (Jan)                    │
│ %d          │ Day of month (01-31)                      │
│ %A          │ Full weekday name (Monday)                │
│ %a          │ Short weekday name (Mon)                  │
│ %H          │ Hour 24-hour (00-23)                      │
│ %I          │ Hour 12-hour (01-12)                      │
│ %M          │ Minute (00-59)                            │
│ %S          │ Second (00-59)                            │
│ %p          │ AM/PM                                     │
│ %f          │ Microsecond (000000-999999)               │
│ %z          │ Timezone offset                           │
│ %Z          │ Timezone name                             │
└─────────────┴────────────────────────────────────────────┘
""")


# ============================================================
# STRPTIME - String to Date
# ============================================================

print("\n3. STRPTIME - String to Date")

# Parse strings to datetime
date_str1 = "2024-12-25"
parsed1 = datetime.strptime(date_str1, "%Y-%m-%d")
print(f"   '{date_str1}' -> {parsed1}")

date_str2 = "25/12/2024"
parsed2 = datetime.strptime(date_str2, "%d/%m/%Y")
print(f"   '{date_str2}' -> {parsed2}")

date_str3 = "December 25, 2024"
parsed3 = datetime.strptime(date_str3, "%B %d, %Y")
print(f"   '{date_str3}' -> {parsed3}")

# With time
date_str4 = "2024-12-25 14:30:45"
parsed4 = datetime.strptime(date_str4, "%Y-%m-%d %H:%M:%S")
print(f"   '{date_str4}' -> {parsed4}")


# ============================================================
# ISOFORMAT
# ============================================================

print("\n4. ISOFORMAT")

now = datetime.now()
print(f"   ISO format: {now.isoformat()}")
print(f"   ISO date: {now.date().isoformat()}")
print(f"   ISO time: {now.time().isoformat()}")

Formatting key points:

  • strftime(format) — convert date to string
  • strptime(string, format) — convert string to date
  • Common codes — %Y, %m, %d, %H, %M, %S
  • isoformat() — standard ISO format

Quick Check: What function converts a date to a string? (Answer: strftime())

Real-World Example

6

Building an Event Scheduler

# Real-World Example: Event Scheduler

from datetime import datetime, date, timedelta
import calendar

print("=" * 60)
print("EVENT SCHEDULER")
print("=" * 60)

# ============================================================
# EVENT CLASS
# ============================================================

class Event:
    def __init__(self, name, start_datetime, end_datetime, location=""):
        self.name = name
        self.start = start_datetime
        self.end = end_datetime
        self.location = location
    
    def duration(self):
        return self.end - self.start
    
    def is_ongoing(self, now=None):
        if now is None:
            now = datetime.now()
        return self.start <= now <= self.end
    
    def format_date(self):
        return self.start.strftime("%A, %B %d, %Y")
    
    def format_time(self):
        start_str = self.start.strftime("%I:%M %p")
        end_str = self.end.strftime("%I:%M %p")
        return f"{start_str} - {end_str}"
    
    def __repr__(self):
        return f"{self.name}: {self.format_date()} at {self.format_time()}"


# ============================================================
# SCHEDULER CLASS
# ============================================================

class Scheduler:
    def __init__(self):
        self.events = []
    
    def add_event(self, event):
        self.events.append(event)
    
    def get_events_by_date(self, target_date):
        """Get all events on a specific date"""
        return [e for e in self.events if e.start.date() == target_date]
    
    def get_upcoming_events(self, days=7):
        """Get events in the next N days"""
        now = datetime.now()
        future = now + timedelta(days=days)
        return [e for e in self.events if now <= e.start <= future]
    
    def get_events_in_month(self, year, month):
        """Get all events in a specific month"""
        return [e for e in self.events 
                if e.start.year == year and e.start.month == month]
    
    def print_month_calendar(self, year, month):
        """Print a calendar for a month with events"""
        print(f"\n   Calendar for {datetime(year, month, 1).strftime('%B %Y')}")
        print("   " + "-" * 30)
        
        # Get events for this month
        month_events = self.get_events_in_month(year, month)
        event_dates = {e.start.day: e for e in month_events}
        
        # Print calendar
        cal = calendar.monthcalendar(year, month)
        print("   Mo Tu We Th Fr Sa Su")
        
        for week in cal:
            week_str = "   "
            for day in week:
                if day == 0:
                    week_str += "   "
                elif day in event_dates:
                    week_str += f"*{day:2d}"
                else:
                    week_str += f" {day:2d}"
            print(week_str)
        
        # Print event details
        if month_events:
            print("\n   Events this month:")
            for event in month_events:
                print(f"      {event.format_date()}: {event.name} ({event.format_time()})")


# ============================================================
# DEMONSTRATION
# ============================================================

print("\n1. CREATING EVENTS")

scheduler = Scheduler()

# Create some events
events = [
    Event("Team Meeting", 
          datetime(2024, 6, 15, 10, 0), 
          datetime(2024, 6, 15, 11, 0),
          "Conference Room A"),
    
    Event("Lunch with Client",
          datetime(2024, 6, 16, 12, 30),
          datetime(2024, 6, 16, 14, 0),
          "Downtown Cafe"),
    
    Event("Python Workshop",
          datetime(2024, 6, 20, 9, 0),
          datetime(2024, 6, 20, 17, 0),
          "Training Center"),
    
    Event("Project Review",
          datetime(2024, 6, 22, 15, 0),
          datetime(2024, 6, 22, 16, 30),
          "Meeting Room B"),
    
    Event("Conference",
          datetime(2024, 7, 10, 8, 0),
          datetime(2024, 7, 12, 18, 0),
          "Convention Center")
]

for event in events:
    scheduler.add_event(event)
    print(f"   Added: {event}")

print("\n2. EVENTS BY DATE")
target_date = date(2024, 6, 15)
events_today = scheduler.get_events_by_date(target_date)
print(f"   Events on {target_date}:")
for event in events_today:
    print(f"      {event.name}: {event.format_time()}")

print("\n3. UPCOMING EVENTS (next 7 days)")
upcoming = scheduler.get_upcoming_events(7)
print(f"   Upcoming events:")
for event in upcoming:
    print(f"      {event.format_date()}: {event.name}")

print("\n4. EVENT DURATIONS")
for event in events:
    duration = event.duration()
    print(f"   {event.name}: {duration}")

print("\n5. CURRENT EVENT STATUS")
now = datetime.now()
print(f"   Current time: {now}")
for event in events:
    status = "ONGOING" if event.is_ongoing(now) else "upcoming"
    print(f"   {event.name}: {status}")

print("\n6. MONTH CALENDAR")
scheduler.print_month_calendar(2024, 6)

print("\n" + "=" * 60)
print("KEY TAKEAWAYS:")
print("=" * 60)
print("""
- datetime module makes date/time handling easy
- Combine date and time for full timestamps
- timedelta for date arithmetic
- strftime/strptime for formatting
- Build useful applications like schedulers
""")

Real-world example key points:

  • Event class — stores name, start, end
  • Scheduler — manages events
  • Filter by date — get events by date
  • Upcoming events — filter by time
  • Calendar view — visual representation

Quick Check: How would you find events in the next 7 days? (Answer: Filter events where start < now + timedelta(days=7))

Best Practices

7

Using Datetime Effectively

# Best Practices for Datetime

from datetime import datetime, date, timedelta

print("=" * 60)
print("BEST PRACTICES FOR DATETIME")
print("=" * 60)

# ============================================================
# 1. STORE DATES AS DATE/DATETIME OBJECTS
# ============================================================

print("\n1. STORE DATES AS DATE/DATETIME OBJECTS")

# Good - store as datetime
birthday = date(1990, 5, 15)
now = datetime.now()
age = now.year - birthday.year
print(f"   Age: {age}")

# Bad - store as string
birthday_str = "1990-05-15"
# Cannot easily calculate age from string!

# ============================================================
# 2. USE UTC FOR CONSISTENCY
# ============================================================

print("\n2. USE UTC FOR CONSISTENCY")

# Good - use UTC
utc_now = datetime.utcnow()
print(f"   UTC now: {utc_now}")

# Local time is also fine for simple apps
local_now = datetime.now()
print(f"   Local now: {local_now}")

# ============================================================
# 3. USE ISO FORMAT FOR EXCHANGE
# ============================================================

print("\n3. USE ISO FORMAT FOR EXCHANGE")

# Good - ISO format is standard
now = datetime.now()
iso_str = now.isoformat()
print(f"   ISO format: {iso_str}")

# Convert back
parsed = datetime.fromisoformat(iso_str)
print(f"   Parsed back: {parsed}")

# ============================================================
# 4. VALIDATE DATES
# ============================================================

print("\n4. VALIDATE DATES")

def validate_date(year, month, day):
    try:
        d = date(year, month, day)
        return True, d
    except ValueError as e:
        return False, str(e)

valid, result = validate_date(2024, 2, 29)  # Leap year
print(f"   2024-02-29 valid: {valid}")

valid, result = validate_date(2023, 2, 29)  # Not a leap year
print(f"   2023-02-29 valid: {valid}")

# ============================================================
# 5. BE CAREFUL WITH TIMEDELTA AND MONTHS
# ============================================================

print("\n5. BE CAREFUL WITH TIMEDELTA AND MONTHS")

# timedelta only handles days, not months
from dateutil.relativedelta import relativedelta

print("   For month operations, consider using dateutil")

# ============================================================
# 6. USE DATETIME FOR TIMEZONES
# ============================================================

print("\n6. USE DATETIME FOR TIMEZONES")

# Python 3.9+ supports timezone
from datetime import timezone

# Create timezone-aware datetime
aware = datetime.now(timezone.utc)
print(f"   Timezone-aware: {aware}")

# ============================================================
# 7. SUMMARY
# ============================================================

print("\n" + "=" * 60)
print("BEST PRACTICES SUMMARY")
print("=" * 60)
print("""
- Store dates as date/datetime objects, not strings
- Use UTC for consistency across timezones
- Use ISO format for data exchange
- Validate dates before using them
- Use dateutil for month/year arithmetic
- Consider timezone awareness when needed
""")

Best practices summary:

  • Store as objects — not strings
  • Use UTC — for consistency
  • ISO format — for data exchange
  • Validate — check dates are valid
  • Month arithmetic — use dateutil

Quick Check: What format should you use for exchanging dates? (Answer: ISO format - YYYY-MM-DD)

Try It Yourself

Experiment with datetime in the editor below.

Loading Pyodide... 0%
Python Code Editor
==================================================
DATETIME - PRACTICE
==================================================

1. CURRENT DATE AND TIME
Now: 2024-06-15 10:30:45.123456
Today: 2024-06-15

2. CREATE SPECIFIC DATE
Christmas 2024: 2024-12-25
Year: 2024, Month: 12, Day: 25

3. DATE ARITHMETIC
Today: 2024-06-15
+10 days: 2024-06-25
-5 days: 2024-06-10

4. FORMATTING
Default: 2024-06-15 10:30:45.123456
YYYY-MM-DD: 2024-06-15
MM/DD/YYYY: 06/15/2024
Full date: Saturday, June 15, 2024
Time: 10:30 AM
🏆

You've Got It!

You now understand the datetime module in Python. You know how to work with dates, times, format them, and perform date arithmetic.

Quick Quiz

Test what you've learned:

1. How do you get today's date?
2. How do you add 7 days to a date?
3. What function converts a date to a string?
4. What does timedelta represent?
5. What format is recommended for exchanging dates?

Frequently Asked Questions

What is the datetime module in Python? ▼

The datetime module provides classes for working with dates and times. It includes date, time, datetime, timedelta, and timezone classes for handling various date/time operations.

What's the difference between date and datetime? ▼

date stores only the date (year, month, day). datetime stores both date and time. Use date when you only need the date, and datetime when you need both date and time.

How do I convert a string to a datetime object? ▼

Use datetime.strptime(date_string, format). For example: datetime.strptime("2024-12-25", "%Y-%m-%d") converts the string to a datetime object.

How do I get the difference between two dates? ▼

Subtract the two dates/datetimes. The result is a timedelta object. For example: diff = date2 - date1 gives you a timedelta with days, seconds, etc.

What's the recommended date format? ▼

The ISO format (YYYY-MM-DD) is recommended for exchanging dates. It's unambiguous, widely supported, and sorts correctly. Use isoformat() to convert to ISO format.

How do I handle timezones? ▼

Use timezone-aware datetime objects. In Python 3.9+, you can use datetime.now(timezone.utc). For more advanced timezone handling, consider using the pytz library.

Where to Go From Here

Now that you understand the datetime module, check out these related topics:

JSON Module

Learn how to work with JSON data, including dates.

Learn More →

OS Module

Learn about working with the operating system.

Learn More →

Functools Module

Learn about higher-order functions.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: Functools Next: JSON →