Working with Dates and Times
Overview
Many applications require tracking dates, times, or durations. This topic covers using the datetime module to perform calculations, format timestamps, and build programs that rely on scheduling or time tracking, handling temporal data effectively.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- datetime module: Working with dates, times, and timestamps.
- Creating dates: How to create date and datetime objects.
- Formatting dates: Converting dates to strings and parsing strings to dates.
- Time differences: Calculating durations with timedelta.
- Date arithmetic: Adding and subtracting time from dates.
The datetime Module
Python's datetime module provides classes for working with dates and times:
datetime
Date and time together (year, month, day, hour, minute, second)
date
Just the date (year, month, day)
time
Just the time (hour, minute, second)
timedelta
Time differences and durations
from datetime import datetime, date, timedelta
# Get current date and time
now = datetime.now()
print(now) # Output: 2024-01-15 14:30:45.123456
# Create a specific date
birthday = date(2000, 5, 15)
print(birthday) # Output: 2000-05-15
# Calculate time difference
future = datetime.now() + timedelta(days=30)
print(future) # Output: 30 days from now
Formatting Dates
Convert dates to strings and parse strings to dates using format codes:
from datetime import datetime
# Get current date and time
now = datetime.now()
# Format date as string
formatted1 = now.strftime("%B %d, %Y")
print(formatted1) # Output: January 15, 2024
formatted2 = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted2) # Output: 2024-01-15 14:30:45
formatted3 = now.strftime("%A, %B %d, %Y")
print(formatted3) # Output: Monday, January 15, 2024
from datetime import datetime
# Parse string to date
date_string1 = "2024-01-15"
parsed_date1 = datetime.strptime(date_string1, "%Y-%m-%d")
print(parsed_date1) # Output: 2024-01-15 00:00:00
date_string2 = "January 15, 2024"
parsed_date2 = datetime.strptime(date_string2, "%B %d, %Y")
print(parsed_date2) # Output: 2024-01-15 00:00:00
Common Format Codes
| Code | Meaning | Example |
|---|---|---|
%Y |
4-digit year | 2024 |
%m |
Month as number (01-12) | 01 |
%d |
Day of month (01-31) | 15 |
%B |
Full month name | January |
%A |
Full weekday name | Monday |
%H |
Hour (00-23) | 14 |
%M |
Minute (00-59) | 30 |
%S |
Second (00-59) | 45 |
Time Differences and Calculations
Use timedelta to work with time differences:
from datetime import datetime, timedelta
# Get current time
now = datetime.now()
print(f"Now: {now}")
# Add time
future = now + timedelta(days=30)
print(f"30 days from now: {future}")
# Subtract time
past = now - timedelta(hours=5)
print(f"5 hours ago: {past}")
# Calculate difference
date1 = datetime(2024, 1, 1)
date2 = datetime(2024, 1, 15)
difference = date2 - date1
print(f"Difference: {difference.days} days")
timedelta Parameters
You can specify days, seconds, microseconds, milliseconds, minutes, hours, or weeks:
timedelta(days=7)- 7 daystimedelta(hours=24)- 24 hourstimedelta(weeks=2)- 2 weekstimedelta(days=1, hours=12)- 1.5 days
Practice: Working with Dates
Try It YourselfTry working with dates and times:
What happened? You created a date, formatted it as a string, calculated the difference between dates, and added time using timedelta.
Working with Timezones
For applications that need timezone awareness:
from datetime import datetime
import pytz # Need to install: pip install pytz
# Create timezone-aware datetime
utc = pytz.UTC
now_utc = datetime.now(utc)
print(f"UTC time: {now_utc}")
# Convert to different timezone
ny_tz = pytz.timezone('America/New_York')
ny_time = now_utc.astimezone(ny_tz)
print(f"New York time: {ny_time}")
Note
For most beginner projects, you don't need timezones. But if you're building applications that work across regions, timezone handling becomes important!
Common Date/Time Operations
Here are common operations you'll perform:
from datetime import datetime
def calculate_age(birth_date):
today = datetime.now()
age = today.year - birth_date.year
# Adjust if birthday hasn't occurred this year
if (today.month, today.day) < (birth_date.month, birth_date.day):
age -= 1
return age
birthday = datetime(2000, 5, 15)
age = calculate_age(birthday)
print(f"Age: {age} years")
from datetime import datetime, timedelta
def days_between(date1, date2):
return abs((date2 - date1).days)
start = datetime(2024, 1, 1)
end = datetime(2024, 12, 31)
days = days_between(start, end)
print(f"Days between: {days}")
from datetime import datetime, timedelta
def get_next_weekday(date, weekday):
"""Get next occurrence of weekday (0=Monday, 6=Sunday)"""
days_ahead = weekday - date.weekday()
if days_ahead <= 0:
days_ahead += 7
return date + timedelta(days=days_ahead)
today = datetime.now()
next_monday = get_next_weekday(today, 0)
print(f"Next Monday: {next_monday.strftime('%B %d, %Y')}")
Summary
In this lesson, you learned:
- datetime module: Classes for dates, times, and durations
- Creating dates: Use
datetime.now()ordatetime(year, month, day) - Formatting: Use
strftime()to format,strptime()to parse - Time differences: Use
timedeltafor calculations - Date arithmetic: Add/subtract
timedeltafrom dates - Common operations: Age calculation, days between dates, weekday operations
Remember
Dates and times are essential for many applications - logging, scheduling, data analysis, timestamps. The datetime module makes it easy to work with temporal data. Practice with common operations like calculating ages and finding date differences!
End-of-Lesson Exercises
Think about these questions to reinforce what you've learned:
Exercise 1: datetime Classes
What are the main classes in the datetime module? What does each one represent?
Exercise 2: Date Operations
How would you calculate a date 30 days from now? How would you format it as "January 15, 2024"?