Time in Python: datetime & time

Published: April 5, 2026 | Category: Programming Time

Python provides two main modules in the standard library for dealing with time: time and datetime. Understanding the relationship between these two is key to writing reliable Python applications.

The `time` Module: Low-Level Access

The time module provides low-level functions that interface directly with the operating system's time services. It primarily returns time in seconds as a floating-point number since the **Unix Epoch**.

import time
print(time.time()) # Output: 1712290400.1234
        

This is ideal for measuring performance (benchmarking) or interacting with low-level kernel APIs.

The `datetime` Module: Object-Oriented Design

For most application logic, datetime is the preferred choice. It provides classes for manipulating dates, times, and time zones in a more human-friendly, object-oriented way.

  • datetime.date: Represents a date (Year, Month, Day) without time.
  • datetime.time: Represents a time (Hour, Minute, Second, Microsecond).
  • datetime.datetime: A combination of both date and time.
  • datetime.timedelta: Represents a duration of time (difference between two dates).

Naive vs. Aware Datetime

One of the biggest pitfalls for Python developers is the "naive" datetime object. By default, datetime.now() has no timezone information. It assumes the local system's time.

Modern applications should use "aware" objects, which include offset information from UTC.

from datetime import datetime, timezone
now = datetime.now(timezone.utc) # An 'aware' UTC datetime
        

Conclusion

While Python's standard library is powerful, many developers use the third-party pytz or pendulum libraries for even more robust handling of complex timezones and human-readable durations. For those looking forward, Python 3.9+ added zoneinfo to the standard library, finally bringing native IANA timezone support to Python.