Remember
Use date objects for calendar dates and timedelta for durations. Adding a duration creates a new date rather than changing the old one.
Use date objects for calendar dates and timedelta for durations. Adding a duration creates a new date rather than changing the old one.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
from datetime import date, timedelta
start = date(2026, 1, 30)
finish = start + timedelta(days=3)
print(start)
print(finish)Top-level scope
class dateObject 2 · typeclass timedeltaObject 3 · datedatetime.date(2026, 1, 30)Object 4 · datedatetime.date(2026, 2, 2)Use date objects for calendar dates and timedelta for durations. Adding a duration creates a new date rather than changing the old one.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
from datetime import date, timedelta
start = date(2026, 1, 30)
finish = start + timedelta(days=3)
print(start)
print(finish)
|
v
DISPLAYED RESULT
2026-01-30
2026-02-02
FINAL BINDINGS
date --> object 1 (type)
timedelta --> object 2 (type)
start --> object 3 (date)
finish --> object 4 (date)
object 1: class date
object 2: class timedelta
object 3: datetime.date(2026, 1, 30)
object 4: datetime.date(2026, 2, 2)Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
from datetime import date, timedelta
start = date(2026, 1, 30)
finish = start + timedelta(days=3)
print(start)
print(finish)Top-level scope
class dateObject 2 · typeclass timedeltaObject 3 · datedatetime.date(2026, 1, 30)Object 4 · datedatetime.date(2026, 2, 2)The example has finished. Compare the final output with the values and references above.
2026-01-30 2026-02-02
What do you expect this program to print?
from datetime import date, timedelta
start = date(2026, 1, 30)
finish = start + timedelta(days=3)
print(start)
print(finish)Time is a crucial element in programming — whether you're logging events, calculating durations, or scheduling tasks. Python makes handling dates and times easy and intuitive with its built-in datetime module. This tutorial walks you through the foundational concepts of datetime and shows you how to effectively use it in your code.
To begin working with dates and times, you first need to import the datetime module:
import datetime
This gives you access to classes like datetime, date, time, and timedelta.
The date class lets you represent and manipulate dates (year, month, day).
from datetime import date
d = date(2025, 5, 16)
print(d)
2025-05-16
Explanation: This creates a date object for May 16, 2025. The output is in ISO format (YYYY-MM-DD).
Need to get today’s date? Use the today() method.
from datetime import date
today = date.today()
print("Today is:", today)
Today is: 2025-05-16
The datetime class combines both date and time into a single object.
from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
Current date and time: 2025-05-16 08:23:45.123456
Notice that it includes the date, hour, minute, second, and microsecond. Perfect for timestamps.
You can extract parts of the datetime using its attributes.
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)
Year: 2025
Month: 5
Day: 16
Hour: 8
Minute: 23
Second: 45
Use the strftime() method to convert a datetime object into a string with custom formatting.
formatted = now.strftime("%B %d, %Y %I:%M %p")
print("Formatted:", formatted)
Formatted: May 16, 2025 08:23 AM
Note: Use %B for full month name, %d for day, %Y for 4-digit year, etc.
Want to convert a date/time string into a datetime object? Use strptime().
date_str = "2025-05-16 14:30"
dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M")
print(dt)
2025-05-16 14:30:00
timedelta is used to perform date/time arithmetic.
from datetime import timedelta
tomorrow = today + timedelta(days=1)
yesterday = today - timedelta(days=1)
print("Tomorrow:", tomorrow)
print("Yesterday:", yesterday)
Tomorrow: 2025-05-17
Yesterday: 2025-05-15
Let’s measure how long a piece of code takes to run:
start = datetime.now()
# Simulate processing
for _ in range(10**6):
pass
end = datetime.now()
duration = end - start
print("Processing time:", duration)
Processing time: 0:00:00.043200
By default, datetime objects are "naive" (no timezone). You can make them aware using pytz or zoneinfo (Python 3.9+).
from datetime import datetime
from zoneinfo import ZoneInfo
dt = datetime.now(ZoneInfo("Asia/Kolkata"))
print(dt)
2025-05-16 13:55:42.123456+05:30
strptime(). A mismatch throws ValueError.timedelta instead of manual calculations — it handles leap years, daylight saving, etc.strftime does not validate format codes — use only valid directives.The datetime module is one of Python's most powerful and underused tools. From calculating date ranges to logging precise timestamps, it enables developers to write time-sensitive code that is both readable and reliable. By mastering its basics, you're unlocking a vital skill that’s essential for real-world programming.
Connect what you noticed in the example with the idea below.
Use date objects for calendar dates and timedelta for durations. Adding a duration creates a new date rather than changing the old one.
Adding a timedelta mutates the existing date.
This is the misconception to avoid.Reaching the recap and completing the quizzes are separate milestones.