Python datetime Module
Learn to work with dates, times, and durations in Python using the built-in datetime module: the foundation of time-aware programming.
What is the datetime Module?
Python's datetime module is a built-in library that provides classes for creating, manipulating, and formatting dates and times. It ships with every Python installation: no extra install needed.
import datetime
# The module is ready to use immediately
print(datetime.date.today())
Why Dates and Times Matter
Nearly every real-world application handles time: logging events, scheduling tasks, calculating ages, tracking deadlines, and displaying timestamps. Treating dates as plain strings leads to bugs. The datetime module gives you type-safe objects with built-in arithmetic.
The Four Core Classes
The date Class
A date object represents a calendar date with three attributes: year, month, and day. Use date.today() to get the current date, or construct one manually.
from datetime import date
# Today's date
today = date.today()
print(today) # e.g. 2025-07-11
# Build a specific date
birthday = date(2008, 3, 15)
print(birthday.year) # 2008
print(birthday.month) # 3
print(birthday.day) # 15
The time Class
A time object represents a clock reading independent of any date. It stores hour, minute, second, and microsecond using a 24-hour format.
from datetime import time
# 2:30:00 PM in 24-hour format
afternoon = time(14, 30, 0)
print(afternoon) # 14:30:00
print(afternoon.hour) # 14
print(afternoon.minute) # 30
# Midnight (default values)
midnight = time()
print(midnight) # 00:00:00
The datetime Class
The datetime class combines a date and a time into one object. It is the most commonly used class in the module. Use datetime.now() for the current date and time.
from datetime import datetime
# Current date and time
now = datetime.now()
print(now)
# e.g. 2025-07-11 09:45:12.345678
# Construct a specific moment
launch = datetime(2024, 12, 25, 8, 0, 0)
print(launch.date()) # 2024-12-25
print(launch.time()) # 08:00:00
date vs datetime vs time
| date | datetime | time | |
|---|---|---|---|
| Stores date? | ✓ | ✓ | ✕ |
| Stores time? | ✕ | ✓ | ✓ |
| Constructor | date(y, m, d) | datetime(y, m, d, h, min, s) | time(h, min, s) |
| Get current | date.today() | datetime.now() | N/A |
| Arithmetic? | ✓ (with timedelta) | ✓ (with timedelta) | ✕ |
Duration with timedelta
A timedelta represents a span of time: the difference between two dates or datetimes. You can add or subtract timedeltas to shift dates forward or backward.
from datetime import date, timedelta
today = date.today()
one_week = timedelta(days=7)
# One week from now
next_week = today + one_week
print(next_week)
# Difference between two dates
d1 = date(2025, 9, 1)
d2 = date(2025, 6, 1)
diff = d1 - d2
print(diff.days) # 92
Formatting: strftime
The strftime method converts a datetime object into a formatted string. You supply a format string with special %-codes that get replaced by date/time components.
from datetime import datetime
now = datetime.now()
print(now.strftime("%B %d, %Y"))
# e.g. July 11, 2025
print(now.strftime("%I:%M %p"))
# e.g. 09:45 AM
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# e.g. 2025-07-11 09:45:12
Parsing: strptime
strptime is the reverse of strftime: it converts a string into a datetime object. The format string must exactly match the input's layout.
from datetime import datetime
text = "March 15, 2008"
dt = datetime.strptime(text, "%B %d, %Y")
print(dt)
# 2008-03-15 00:00:00
stamp = "2025-07-11 14:30"
dt2 = datetime.strptime(stamp, "%Y-%m-%d %H:%M")
print(dt2.hour) # 14
How to Apply datetime
Example: Age Calculator
Calculate how many days old a person born on March 15, 2008 is today.
from datetime import date
birthday = date(2008, 3, 15)
today = date.today()
age_delta = today - birthday
print(f"You are {age_delta.days} days old!")
# Approximate years
years = age_delta.days // 365
print(f"That's about {years} years.")
Example: Deadline Countdown
Find how many days, hours, and minutes remain until a specific deadline.
from datetime import datetime
deadline = datetime(2025, 12, 31, 23, 59, 59)
now = datetime.now()
remaining = deadline - now
days = remaining.days
hours = remaining.seconds // 3600
mins = (remaining.seconds % 3600) // 60
print(f"{days}d {hours}h {mins}m left")
Example: Formatting a Timestamp
Parse a raw date string from user input, then display it in a friendly format.
from datetime import datetime
# Simulate user input
user_input = "2025-09-01 08:30"
# Parse the string into a datetime object
dt = datetime.strptime(user_input, "%Y-%m-%d %H:%M")
# Format it nicely
friendly = dt.strftime("%A, %B %d at %I:%M %p")
print(friendly)
Common Mistakes
Summary Reference
| Task | Code | Returns |
|---|---|---|
| Today's date | date.today() | date |
| Current date+time | datetime.now() | datetime |
| Build a date | date(2025, 7, 11) | date |
| Add 30 days | dt + timedelta(days=30) | date/datetime |
| Days between | (d2 - d1).days | int |
| Format as string | dt.strftime("%Y-%m-%d") | str |
| Parse from string | datetime.strptime(s, fmt) | datetime |
Question 1 of 5
Which import statement lets you call date.today() directly without a module prefix?
Question 2 of 5
What does the following code print?
from datetime import date, timedelta
d = date(2025, 1, 1) + timedelta(days=31)
print(d)
Question 3 of 5
The method strftime is used to:
Question 4 of 5
What format code would you use in strftime to display the full month name (e.g., "July")?
Question 5 of 5
Given d1 = date(2025, 3, 10) and d2 = date(2025, 3, 1), what is the value of (d1 - d2).days?