Python's datetime module handles dates, times, and time intervals. Think of it as a toolbox for time-related operations: creating dates, calculating differences, formatting dates for display, and parsing dates from strings. Real-world uses include: logging events, scheduling tasks, calculating ages, and tracking durations.
# DateTime module examples
from datetime import datetime, date, time, timedelta
import calendar
print("DATETIME MODULE EXPLORATION")
print("=" * 50)
# Example 1: Getting current date and time
print("\n1. CURRENT DATE AND TIME")
print("-" * 25)
now = datetime.now()
today = date.today()
current_time = datetime.now().time()
print(f"Current datetime: {now}")
print(f"Date only: {today}")
print(f"Time only: {current_time}")
print(f"Year: {now.year}")
print(f"Month: {now.month} ({now.strftime('%B')})")
print(f"Day: {now.day}")
print(f"Hour: {now.hour}")
print(f"Minute: {now.minute}")
print(f"Second: {now.second}")
# Example 2: Creating specific dates
print("\n\n2. CREATING SPECIFIC DATES")
print("-" * 25)
# Creating a specific date
birthday = date(1995, 8, 15)
print(f"Birthday: {birthday}")
print(f"Birthday year: {birthday.year}")
print(f"Birthday day of week: {birthday.strftime('%A')}")
# Creating a specific datetime
meeting_time = datetime(2024, 3, 15, 14, 30, 0)
print(f"\nMeeting time: {meeting_time}")
print(f"Meeting in 12-hour format: {meeting_time.strftime('%I:%M %p')}")
# Example 3: Date formatting
print("\n\n3. DATE FORMATTING")
print("-" * 25)
print("Different date formats:")
print(f"Default: {now}")
print(f"DD/MM/YYYY: {now.strftime('%d/%m/%Y')}")
print(f"MM/DD/YYYY: {now.strftime('%m/%d/%Y')}")
print(f"YYYY-MM-DD: {now.strftime('%Y-%m-%d')}")
print(f"Full date: {now.strftime('%A, %B %d, %Y')}")
print(f"Time only: {now.strftime('%H:%M:%S')}")
print(f"12-hour time: {now.strftime('%I:%M:%S %p')}")
# Example 4: Parsing dates from strings
print("\n\n4. PARSING DATES FROM STRINGS")
print("-" * 25)
date_string = "2024-03-15 14:30:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Original string: {date_string}")
print(f"Parsed datetime: {parsed_date}")
print(f"Parsed date type: {type(parsed_date)}")
# Example 5: Date arithmetic
print("\n\n5. DATE ARITHMETIC")
print("-" * 25)
# Adding and subtracting time
print("Date calculations:")
print(f"Today: {today}")
print(f"Tomorrow: {today + timedelta(days=1)}")
print(f"Yesterday: {today - timedelta(days=1)}")
print(f"Next week: {today + timedelta(weeks=1)}")
print(f"3 days, 5 hours from now: {now + timedelta(days=3, hours=5)}")
# Calculating age
birth_date = date(1995, 8, 15)
age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
print(f"\nBirth date: {birth_date}")
print(f"Age: {age} years")
# Example 6: Time differences
print("\n\n6. TIME DIFFERENCES")
print("-" * 25)
# Calculate difference between two dates
start_date = date(2024, 1, 1)
days_passed = (today - start_date).days
print(f"Days since Jan 1, 2024: {days_passed} days")
# Calculate time until next birthday
next_birthday = date(today.year, birth_date.month, birth_date.day)
if today > next_birthday:
next_birthday = date(today.year + 1, birth_date.month, birth_date.day)
days_to_birthday = (next_birthday - today).days
print(f"\nNext birthday: {next_birthday}")
print(f"Days until next birthday: {days_to_birthday}")
# Example 7: Calendar operations
print("\n\n7. CALENDAR OPERATIONS")
print("-" * 25)
# Generate calendar for a month
cal = calendar.month(2024, 3)
print(f"Calendar for March 2024:\n{cal}")
# Check if a year is a leap year
print(f"\nIs 2024 a leap year? {calendar.isleap(2024)}")
print(f"Is 2025 a leap year? {calendar.isleap(2025)}")
# Example 8: Real-world application - Task Scheduler
print("\n\n8. REAL-WORLD APPLICATION: TASK SCHEDULER")
print("-" * 25)
class TaskScheduler:
def __init__(self):
self.tasks = []
def add_task(self, task_name, due_date):
"""Add a task with due date"""
self.tasks.append({
'name': task_name,
'due_date': due_date,
'added': datetime.now()
})
print(f"Task '{task_name}' added (Due: {due_date.strftime('%Y-%m-%d')})")
def show_upcoming_tasks(self, days=7):
"""Show tasks due in next N days"""
print(f"\nTasks due in next {days} days:")
print("-" * 40)
upcoming_tasks = []
for task in self.tasks:
days_until_due = (task['due_date'].date() - today).days
if 0 <= days_until_due <= days:
upcoming_tasks.append((task['name'], task['due_date'], days_until_due))
if not upcoming_tasks:
print("No upcoming tasks!")
else:
for name, due_date, days_left in sorted(upcoming_tasks, key=lambda x: x[2]):
status = "TODAY!" if days_left == 0 else f"in {days_left} days"
print(f"• {name}: {due_date.strftime('%Y-%m-%d')} ({status})")
# Create scheduler and add tasks
scheduler = TaskScheduler()
scheduler.add_task("Pay bills", date(2024, 3, 20))
scheduler.add_task("Doctor appointment", date(2024, 3, 18))
scheduler.add_task("Submit report", today) # Due today!
scheduler.add_task("Plan vacation", date(2024, 4, 1))
# Show upcoming tasks
scheduler.show_upcoming_tasks(10)
# Example 9: Timezone awareness (basic)
print("\n\n9. WORKING WITH TIMEZONES (BASIC)")
print("-" * 25)
# Note: For advanced timezone handling, use pytz library
print("Current UTC time:")
utc_now = datetime.utcnow()
print(f"UTC: {utc_now}")
print(f"Local: {now}")
print(f"Difference: {(now - utc_now)}")
# Example 10: Measuring execution time
print("\n\n10. MEASURING EXECUTION TIME")
print("-" * 25)
import time
print("Measuring how long code takes to run:")
start_time = time.time()
# Simulate some work
result = 0
for i in range(1000000):
result += i
end_time = time.time()
execution_time = end_time - start_time
print(f"Calculation took: {execution_time:.4f} seconds")