DateTime Module - Working with Dates and Times
The datetime module is like a digital calendar, clock, and stopwatch all in one. It helps you track dates, times, calculate differences, and schedule events - just like your phone's calendar app.
The `datetime` module is Python's built‑in toolbox for handling dates, times, and time intervals. It provides classes like `date`, `time`, `datetime`, `timedelta`, and `timezone`. Real‑world uses include logging events, calculating ages, scheduling tasks, formatting timestamps, and parsing date strings from user input or APIs.
**Key classes:**
- `date` – year, month, day.
- `time` – hour, minute, second, microsecond.
- `datetime` – combination of date and time.
- `timedelta` – difference between two dates/times (e.g., 5 days, 3 hours).
- `tzinfo` – time zone information (advanced).
**Getting current date/time:**
```python
from datetime import datetime, date, time, timedelta
now = datetime.now() # current date and time
today = date.today() # current date (year, month, day)
current_time = datetime.now().time() # just the time
```
**Creating specific dates/times:**
```python
birthday = date(1995, 8, 15)
meeting = datetime(2024, 3, 15, 14, 30, 0)
```
**Formatting dates (`.strftime()`):**
Converts a date/time object to a string using format codes. Common codes:
- `%Y` – four‑digit year
- `%m` – two‑digit month (01‑12)
- `%d` – two‑digit day (01‑31)
- `%H` – hour (00‑23)
- `%I` – hour (01‑12)
- `%M` – minute (00‑59)
- `%S` – second (00‑59)
- `%p` – AM/PM
- `%A` – full weekday name
- `%B` – full month name
Example: `now.strftime("%A, %B %d, %Y")` → `"Friday, March 15, 2024"`.
**Parsing dates from strings (`.strptime()`):**
Converts a string to a datetime object when you know the format.
```python
date_string = "2024-03-15 14:30:00"
parsed = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
```
**Date arithmetic with `timedelta`:**
Add or subtract days, hours, minutes, etc.
```python
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)
in_3_hours = now + timedelta(hours=3)
```
**Calculating differences:**
Subtracting two datetime objects returns a `timedelta` object.
```python
difference = later_date - earlier_date
print(difference.days, difference.seconds)
```
**Calendar module:**
The `calendar` module provides additional utilities:
- `calendar.month(year, month)` – returns a formatted calendar string.
- `calendar.isleap(year)` – checks if a year is a leap year.
- `calendar.weekday(year, month, day)` – returns day of week (Monday=0).
**Time measurement (performance):**
Use `time.time()` to get seconds since epoch (Unix time). Subtract to measure elapsed time.
```python
import time
start = time.time()
# ... code to measure ...
elapsed = time.time() - start
```
**Common mistakes:**
- Forgetting to import the classes (`from datetime import datetime` vs `import datetime`).
- Using wrong format codes (case‑sensitive).
- Parsing a date string without matching the format exactly – raises `ValueError`.
- Mixing naive and aware datetimes (timezone handling is more advanced).
**Practice exercises:**
1. Print today's date in format "YYYY‑MM‑DD".
2. Calculate how many days until your next birthday.
3. Create a list of the next 7 days starting from today.
4. Ask the user for their birth date (year, month, day) and print their age.
5. Measure how long it takes to compute the sum of numbers from 1 to 1,000,000.
**Real‑world applications:**
- Logging timestamps for events.
- Countdown timers and reminders.
- Age calculators (e.g., on websites).
- Scheduling reports (e.g., run every Monday).
- Converting between time zones (requires `pytz` library).
- Parsing dates from CSV files or API responses.
# ========== EXAMPLE 1: Getting Current Date/Time and Formatting ==========
from datetime import datetime, date, time, timedelta
import calendar
print("=== Example 1: Current Date/Time and Formatting ===")
now = datetime.now()
today = date.today()
print(f"Current datetime: {now}")
print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}")
print(f"Hour: {now.hour}, Minute: {now.minute}, Second: {now.second}")
print(f"Formatted (DD/MM/YYYY): {now.strftime('%d/%m/%Y')}")
print(f"Full weekday: {now.strftime('%A, %B %d, %Y')}")
print(f"12-hour time: {now.strftime('%I:%M %p')}")
print()
# ========== EXAMPLE 2: Date Arithmetic (timedelta) and Age Calculation ==========
print("=== Example 2: Date Arithmetic and Age Calculation ===")
# Create a specific date
birthday = date(1995, 8, 15)
print(f"Birthday: {birthday}")
print(f"Day of week: {birthday.strftime('%A')}")
# Calculate age
today = date.today()
age = today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day))
print(f"Current age: {age} years")
# Calculate days until next birthday
next_bday = date(today.year, birthday.month, birthday.day)
if next_bday < today:
next_bday = date(today.year + 1, birthday.month, birthday.day)
days_left = (next_bday - today).days
print(f"Next birthday: {next_bday} (in {days_left} days)")
# Adding/subtracting timedelta
print(f"\nTomorrow: {today + timedelta(days=1)}")
print(f"1 week ago: {today - timedelta(weeks=1)}")
print()
# ========== EXAMPLE 3: Parsing Dates, Calendar, and Execution Time ==========
print("=== Example 3: Parsing Strings, Calendar, and Measuring Time ===")
# Parse a date from a string
date_str = "2024-12-25 09:30:00"
parsed = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(f"Parsed date: {parsed}")
print(f"Is Christmas? {parsed.strftime('%B %d')}")
# Generate a calendar
print("\nCalendar for December 2024:")
print(calendar.month(2024, 12))
# Check leap year
print(f"Is 2024 leap year? {calendar.isleap(2024)}")
# Measure execution time
import time
start = time.time()
total = 0
for i in range(1, 1000001):
total += i
end = time.time()
print(f"\nSum 1 to 1,000,000 = {total}")
print(f"Calculation took: {end - start:.4f} seconds")
→ Run this code interactively