time | Python Standard Library – Real Python
The Python time module provides various time-related functions. It allows you to work with time in a variety of ways, including getting the current time, measuring execution durations, and working with time in seconds since the epoch (January 1, 1970, 00:00:00 UTC).
Here’s a quick example:
Key Features
- Retrieves the current time
- Formats and parses time strings
- Measures elapsed time with high precision
- Pauses execution for a given number of seconds
- Converts between time representations (seconds, tuples, strings)
- Obtains system time in UTC or local time
- Works with monotonic clocks for reliable timing
- Supports sleep with subsecond precision
Frequently Used Classes and Functions
Examples
Get the time since epoch:
Pause execution for two seconds:
Format the current time as a string:
Measure elapsed time with high precision:
Common Use Cases
- Measuring the duration of code execution
- Formatting and displaying the current date and time
- Scheduling tasks or delays at specific intervals
- Converting between different time representations
- Benchmarking and profiling code performance
- Implementing retries with delays
- Creating timeouts or intervals in programs
- Simulating delays in tests, scripts, or teaching examples
- Generating timestamps for logs or filenames
Real-World Example
Suppose you want to measure the execution time of a block of code to optimize performance. Here’s how you can achieve that using the time module:
In this example, the time module helps you measure how long a task takes to execute, which is valuable for performance tuning and optimization.
Tutorial
How to Get and Use the Current Time in Python
In this tutorial, you'll be getting the current time in Python. You'll get your hands on a datetime object that represents the current time. You'll see how to format it according to international standards, and you'll even check out how computers represent time.
For additional information on related topics, take a look at the following resources: