Dates, times, and durations
Programs that deal with real-world activity almost always need a sense of time. Whether we are timestamping generated files, measuring how long a task takes, or comparing events, Python’s standard library gives us simple tools to work with dates and times in a reliable way. This lesson orients us to those tools so we can recognize when and how to use them in practical programs.
Representing dates and times in Python
Python represents dates and times using types from the datetime module. These types model calendar dates, clock times, or a combination of both.
The most commonly used type is datetime, which represents a specific moment in time.
from datetime import datetime
published_at = datetime(2026, 3, 14, 9, 30)
This value represents a concrete date and time that we can store, pass around, and compare like any other object.
Getting the current date and time
Many programs need to know “now”. The datetime type provides a direct way to capture the current date and time at runtime.
from datetime import datetime
now = datetime.now()
This snapshot is often used for timestamps, filenames, or logging when a piece of work was performed.
Representing durations and time intervals
Durations are represented using the timedelta type. A timedelta expresses a span of time rather than a specific moment.
from datetime import timedelta
build_time = timedelta(seconds=3)
Durations are commonly added to or subtracted from dates and times to compute future or past moments.
Comparing dates and times
Date and time values can be compared directly. This makes it easy to order events or check whether something happened before or after another moment.
from datetime import datetime
start = datetime(2026, 3, 14, 9, 30)
end = datetime(2026, 3, 14, 9, 45)
is_finished = end > start
These comparisons behave the way we expect, following calendar and clock order.
Measuring elapsed time
A common use of dates and times is measuring how long something takes to run. We do this by capturing a start time, performing some work, and then capturing an end time.
from datetime import datetime
started = datetime.now()
# generate a small HTML page here
finished = datetime.now()
elapsed = finished - started
The result of subtracting two datetime values is a timedelta, which represents the elapsed duration.
Conclusion
We now know how Python represents moments in time, how to obtain the current date and time, and how to work with durations. We can compare timestamps and measure elapsed time, which is enough to recognize when these tools belong in a real program. With this orientation, we are ready to apply dates and times naturally as our programs begin to interact with the real world.