- 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
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
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
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
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
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
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
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.
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:
Frequently Asked Questions
What is the datetime module in Python?
What's the difference between date and datetime?
How do I convert a string to a datetime object?
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?
diff = date2 - date1 gives you a timedelta with days, seconds, etc.
What's the recommended date format?
isoformat() to convert to ISO format.
How do I handle timezones?
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 →