Working with Dates and Times in Python with datetime

Python Standard Library

Working with Dates and Times in Python with datetime

Python’s datetime module is one of those tools that seems simple at first and then slowly reveals how much practical work it can do. If you need to move forward in time, measure a duration, parse a date string, or compare timestamps, this is usually the first place to look.

Most common job

Add or subtract a time interval with timedelta.

Most useful habit

Think in terms of “points in time” and “durations.”

Biggest beginner trap

Mixing naive and timezone-aware datetimes without noticing.

The mental model A datetime usually represents a specific point in time. A timedelta represents a duration. Most useful date math is really just moving between those two ideas.
The two core pieces

datetime and timedelta

In practice, most date and time math in Python comes down to these two types:

Type What it represents
datetime A specific date and time
timedelta A duration, such as 3 days or 6 hours

Once that distinction is clear, the rest of the module gets much easier to use.

1. Move forward or backward in time

Adding or subtracting time intervals

One of the most common operations is adding or subtracting a duration from a date or time. Python handles that with timedelta.

from datetime import datetime, timedelta

current_time = datetime.now()
future_time = current_time + timedelta(days=3)
past_time = current_time - timedelta(hours=6)

This is useful for deadlines, countdowns, reminders, expiration windows, and anything else that needs “now plus something” or “now minus something.”

2. Measure a duration

Calculating the difference between two datetimes

If you subtract one datetime from another, Python gives you a timedelta.

from datetime import datetime

start_time = datetime(2023, 5, 1)
end_time = datetime(2023, 5, 10)

duration = end_time - start_time
print(duration)  # 9 days, 0:00:00

This is the operation you use when you want to answer questions like:

  • How long did something take?
  • How many days remain until an event?
  • How far apart are two timestamps?
3. Parse and format dates

Turning strings into datetimes and back

Real programs rarely get dates in perfect Python objects. They usually come in as strings from user input, APIs, files, or databases.

To convert a string into a datetime, use strptime():

from datetime import datetime

date_string = "2023-05-15"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d")

To convert a datetime back into a string, use strftime():

formatted = parsed_date.strftime("%B %d, %Y")
print(formatted)  # May 15, 2023

Parsing and formatting are essential whenever your program needs to exchange dates with the outside world.

4. Compare datetimes

Checking whether one date comes before another

Python lets you compare datetime objects using the usual comparison operators.

from datetime import datetime

date1 = datetime(2023, 5, 15)
date2 = datetime(2023, 5, 20)

if date1 < date2:
    print("date1 is earlier than date2")

This is the basis for scheduling logic, validation, expiration checks, and ordering events in time.

A subtle but important point

Naive vs. timezone-aware datetimes

This is the part beginners often skip, but it matters in real programs.

A naive datetime has no timezone information attached. An aware datetime includes timezone information and can represent a specific moment more unambiguously.

Why this matters If your code stays local and simple, naive datetimes may feel fine. But once time zones, APIs, daylight saving changes, or systems in different regions enter the picture, aware datetimes become much safer.

Modern Python also provides zoneinfo for working with real IANA time zones. The official docs point to it as the standard-library timezone solution.

Common mistake

Changing a component is not the same as changing the datetime

This is a subtle issue in many beginner examples. If you write:

from datetime import datetime

current_date = datetime.now()
future_year = current_date.year + 1

you are not creating a new future datetime. You are only calculating a new integer value for the year.

That can still be useful, but it is different from creating a new date object. It is better to explain that distinction clearly so readers do not confuse “date math” with “extracting a number from a date.”

Quick reference

The most useful operations at a glance

Task Example
Get the current datetime datetime.now()
Add time dt + timedelta(days=3)
Subtract time dt - timedelta(hours=6)
Find duration between two datetimes end - start
Parse a string into a datetime datetime.strptime(...)
Format a datetime as a string dt.strftime(...)
Compare two datetimes date1 < date2
Best beginner takeaway You do not need to memorize the whole module. If you understand datetime, timedelta, parsing, formatting, and the naive-versus-aware distinction, you already have the most important practical tools.

Conclusion

Python’s datetime module is not just for printing timestamps. It gives you the building blocks for real date and time work: moving through time, measuring durations, parsing external input, formatting output, and comparing events.

Once you get comfortable with datetime and timedelta, a lot of time-related programming starts to feel much more manageable.

Raell Dottin

Comments