Working with Dates & Time
Master date and time operations in Python. Learn datetime, timedelta, formatting, and timezone handling.
Master date and time operations in Python. Learn datetime, timedelta, formatting, and timezone handling. This hands-on tutorial focuses on practical implementation of working with dates & time concepts.
Working with Dates & Time
Python's datetime module provides powerful tools for working with dates and times.
The datetime Module
The datetime module is the standard way to work with dates in Python. It provides three main classes:
date: Stores year, month, and day.time: Stores hour, minute, second, microsecond.datetime: Stores both date and time components.
Example
from datetime import datetime
now = datetime.now()
print(now) # Output: 2024-03-15 14:30:00.123456
Date Arithmetic with timedelta
Often you need to calculate future or past dates (e.g., "7 days from now"). The timedelta class represents a duration or difference between two dates.
Example
from datetime import datetime, timedelta
today = datetime.now()
tomorrow = today + timedelta(days=1)
Formatting Dates: strftime
Definition: strftime (String Format Time) converts a datetime object into a readable string using format codes.
| Code | Description | Example |
|---|---|---|
| %Y | Year (4 digits) | 2024 |
| %m | Month (01–12) | 12 |
| %d | Day (01–31) | 25 |
| %H | Hour (00–23) | 14 |
| %M | Minute (00–59) | 30 |
Example
now = datetime.now()
print(now.strftime("%Y-%m-%d")) # Output: 2024-12-25
Parsing Dates: strptime
Definition: strptime (String Parse Time) does the opposite of strftime. It converts a string into a datetime object.
You must provide the format string that matches the structure of your date string.
Example
date_string = "25/12/2024"
date_obj = datetime.strptime(date_string, "%d/%m/%Y")
Coding Challenge: Age Calculator
AI Mentor
Confused about "Python datetime timedelta date formatting"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3Which module handles dates and times?
Key Takeaways
✅ datetime.now() gets current date and time.
✅ timedelta for date arithmetic (add/subtract).
✅ strftime formats datetime as string.
✅ strptime parses string to datetime.
Keep coding! 🚀