Time is one of the most critical resources in any application. Whether you need to measure a function’s performance, create strategic pauses in a script, or record the exact moment a transaction occurs, knowing how to work with time is essential. The time module is part of Python’s standard library, meaning no external installation is needed to get started.
The module focuses on system time and elapsed seconds. Unlike datetime (which handles calendar-aware date objects), time is lower-level and interacts directly with the operating system clock. This makes it ideal for performance measurement and automation tasks. To measure code speed in detail, also see measuring Python code speed with timeit.
Unix timestamp: time.time()
The fundamental concept in the time module is the Unix Timestamp: the number of seconds elapsed since January 1, 1970 at 00:00:00 UTC (known as “The Epoch”). Computers work more easily with a single decimal float than with months of varying lengths or leap years.
import time
now = time.time()
print(f"Current timestamp: {now}")Pausing execution: time.sleep()
time.sleep(seconds) suspends execution for the specified number of seconds. It accepts floats for sub-second precision (e.g. time.sleep(0.5) for 500ms). Useful for rate limiting API calls, creating countdowns, and spacing automated actions:
import timeReading local time: localtime()
import timeFormatting dates: strftime()
strftime() converts a time struct into a formatted string. For a practical project using calendars, see generating a monthly calendar in Python.
import timeMeasuring execution time
import timestrftime format codes reference
| Code | Meaning | Example |
|---|---|---|
| %Y | 4-digit year | 2026 |
| %m | Month (zero-padded) | 06 |
| %d | Day (zero-padded) | 03 |
| %H | Hour (24h) | 14 |
| %M | Minute | 32 |
| %S | Second | 01 |
The full list of format codes is available in the official Python time documentation. For higher-precision benchmarking (with statistical analysis), use timeit instead of raw time.time() differences.
Frequently asked questions
What is the difference between time and datetime?
time deals with seconds and system-level time functions. datetime is higher-level and works with human-readable date/time objects including timezone support, arithmetic, and parsing. For most applications where you need to work with calendar dates, datetime is more convenient.
Can time.sleep() be interrupted?
Yes, by a signal (like KeyboardInterrupt with Ctrl+C). On some systems, sleep may return early if a signal is received. If you need guaranteed timing, check the actual elapsed time after sleep.
The time module is the foundation for any script that needs to interact with the system clock, create delays, or measure performance. Start with time.sleep() and time.time(), which cover 90% of everyday use cases.






