Python datetime Tutorial

Let’s look at datetime tutorial

  1. Notice

    Use date objects for calendar dates and timedelta for durations. Adding a duration creates a new date rather than changing the old one.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
from datetime import date, timedelta
start = date(2026, 1, 30)
finish = start + timedelta(days=3)
print(start)
print(finish)
Live state

Top-level scope

date→Object 1
timedelta→Object 2
start→Object 3
finish→Object 4
Object 1 · typeclass dateObject 2 · typeclass timedeltaObject 3 · datedatetime.date(2026, 1, 30)Object 4 · datedatetime.date(2026, 2, 2)
This step

Use date objects for calendar dates and timedelta for durations. Adding a duration creates a new date rather than changing the old one.

Picture datetime tutorial

Use date objects for calendar dates and timedelta for durations. Adding a duration creates a new date rather than changing the old one.

Image brief

Alt text
A diagram for Python datetime Tutorial. Instructions: from datetime import date, timedelta start = date(2026, 1, 30) finish = start + timedelta(days=3) print(start) print(finish). Displayed result: 2026-01-30 2026-02-02. The final example bindings are 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)
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python datetime Tutorial". Teaching focus: Use date objects for calendar dates and timedelta for durations. Adding a duration creates a new date rather than changing the old one. Depict exactly the relationships and labels in this reference diagram: 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) Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python datetime Tutorial. Instructions: from datetime import date, timedelta start = date(2026, 1, 30) finish = start + timedelta(days=3) print(start) print(finish). Displayed result: 2026-01-30 2026-02-02. The final example bindings are 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)

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
from datetime import date, timedelta
start = date(2026, 1, 30)
finish = start + timedelta(days=3)
print(start)
print(finish)
Live state

Top-level scope

date→Object 1
timedelta→Object 2
start→Object 3
finish→Object 4
Object 1 · typeclass dateObject 2 · typeclass timedeltaObject 3 · datedatetime.date(2026, 1, 30)Object 4 · datedatetime.date(2026, 2, 2)
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
2026-01-30
2026-02-02

What do you expect this program to print?

What does this example display?

from datetime import date, timedelta
start = date(2026, 1, 30)
finish = start + timedelta(days=3)
print(start)
print(finish)
What does this example display?
Choose one answer. You can try again.

Answer and explanation

2026-01-30 2026-02-02

Follow the printed values in order. The output is: 2026-01-30 2026-02-02

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

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.

Introduction to Python datetime

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.

Importing the datetime Module

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.

Creating a Date Object

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).

Today's Date

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

Working with datetime Objects

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.

Accessing Individual Components

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

Formatting Dates and Times

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.

Parsing Strings into datetime Objects

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

Working with Timedelta

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

Measuring Time Durations

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

Handling Time Zones

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

Common Pitfalls & Tips

  • Always verify input formats when using strptime(). A mismatch throws ValueError.
  • Be mindful of time zones in global applications. Naive datetimes can lead to bugs.
  • Use timedelta instead of manual calculations — it handles leap years, daylight saving, etc.
  • strftime does not validate format codes — use only valid directives.

Conclusion

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.

What to remember

Connect what you noticed in the example with the idea below.

Remember

Use date objects for calendar dates and timedelta for durations. Adding a duration creates a new date rather than changing the old one.

Watch out for this idea

Adding a timedelta mutates the existing date.

This is the misconception to avoid.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Python Built-in Functions →