1. The cornerstone of time: ()
() is an entry function to get the timestamp, returning the number of seconds (floating point) since January 1, 1970 (Unix Era). This 10-digit number is like the time dimension ID card, which is the time benchmark in the computer world.
Typical scenario: Program performance analysis
import time def calculate_prime(n): primes = [] for num in range(2, n): is_prime = True for i in range(2, int(num**0.5)+1): if num % i == 0: is_prime = False break if is_prime: (num) return primes start_time = () # Record start timestampprimes = calculate_prime(10000) end_time = () # Record the end time stamp print(f"time consuming:{end_time - start_time:.4f}Second") # Output:time consuming:0.1234Second
Advanced skills: combine context manager to achieve automatic timing
from contextlib import contextmanager @contextmanager def timer(): start = () yield print(f"time consuming:{() - start:.4f}Second") #User Examplewith timer(): data = [x**2 for x in range(1000000)] # Output:time consuming:0.0456Second
2. Time pause technique: ()
(seconds) Let the program enter a dormant state, and the parameters support floating point numbers to achieve millisecond-level control. This is the core method to implement timing tasks and rate limits.
Typical scenario: Data acquisition interval control
import time import requests def fetch_data(): response = ("/data") return () while True: data = fetch_data() print(f"Get data:{len(data)}strip") (60) # Collect once a minute
Notes:
- The actual sleep time may be slightly longer than the parameter value (affected by system scheduling)
- It is necessary to use it in an independent thread in GUI program to avoid interface freezing
3. Time formatting master: ()
Convert timestamps to readable strings and customize the output styles with format code. This is a necessary skill for logging and data display.
Format code quick lookup table:
Code Meaning Example
%Y Four-digit year 2023
%m Month (01-12) 09
%d Date (01-31) 25
%H Hours (24-stage) 14
%M Minutes 30
%S Second 45
%f Microsecond 123456
Typical scenario: Generate standardized log time
import time def log(message): timestamp = ("%Y-%m-%d %H:%M:%S", ()) print(f"[{timestamp}] {message}") log("User login successfully") # Output:[2023-09-25 14:30:45] User login successfully
4. Time difference calculation: time.perf_counter()
A timer with higher accuracy than () designed for performance measurement. Returns a floating point number containing a fraction of seconds, suitable for short interval measurements.
Typical scenario: Algorithm performance comparison
import time def algorithm_a(): # Algorithm A implementation (0.1) def algorithm_b(): # Algorithm B implementation (0.05) start = time.perf_counter() algorithm_a() end = time.perf_counter() print(f"algorithmAtime consuming:{end - start:.6f}Second") start = time.perf_counter() algorithm_b() end = time.perf_counter() print(f"algorithmBtime consuming:{end - start:.6f}Second") #Output:# Algorithm A takes time: 0.100234 seconds# algorithmBtime consuming:0.050123Second
5. Timed task scheduler
Combining () and loop structures, a simple timing task system is implemented. Suitable for lightweight background tasks.
Typical scenario: timed data backup
import time import shutil def backup_data(): ("", "backup/data_backup.db") print("Data backup is completed") while True: current_hour = ().tm_hour if current_hour == 2: # Execute at 2 a.m. backup_data() (3600) # Check once an hourly
Optimization solution: Use schedule library to implement more complex timing tasks
import schedule import time def job(): print("Timed task execution") # Execute at 10:30 every day().("10:30").do(job) while True: schedule.run_pending() (60)
6. Time stamp conversion practice
() and () realize the mutual conversion of timestamps and structured time, which is a key link in data persistence and network transmission.
Typical scenario: parsing log timestamps
import time log_entry = "1695624645: ERROR - Database connection failed" timestamp = int(log_entry.split(":")[0]) # Convert to readable timestruct_time = (timestamp) readable_time = ("%Y-%m-%d %H:%M:%S", struct_time) print(f"Time of error:{readable_time}") # Output:Time of error:2023-09-25 14:30:45
Reverse conversion: Convert structured time to timestamp
import time # Create structured timestruct_time = ("2023-09-25 14:30:45", "%Y-%m-%d %H:%M:%S") # Convert to timestamptimestamp = (struct_time) print(f"Timestamp:{int(timestamp)}") # Output:Timestamp:1695624645
Best Practice Recommendations
- Precision selection: Perf_counter() is used for short-term measurements, and time() is used for long-term intervals.
- Time zone processing: Priority is given to the use of datetime module when multiple time zones are involved
- Blocking operation: Avoid using sleep() directly in GUI or asynchronous programs
- Logging: Always contain timestamp information
- Performance monitoring: combine time and logging module to achieve execution time tracking
Comprehensive case: API call rate limit
import time import requests class APIWrapper: def __init__(self, rate_limit=60): self.rate_limit = rate_limit # Maximum number of requests per minute self.request_times = [] def _check_rate_limit(self): current_time = () # Clean up expired records (keep the last 1 minute request) self.request_times = [t for t in self.request_times if current_time - t < 60] if len(self.request_times) >= self.rate_limit: oldest = self.request_times[0] wait_time = 60 - (current_time - oldest) print(f"Rate limit trigger,wait{wait_time:.2f}Second") (wait_time + 0.1) # Extra buffering time def get(self, url): self._check_rate_limit() response = (url) self.request_times.append(()) return response #User Exampleapi = APIWrapper(rate_limit=60) response = ("/data") print(response.status_code)
Through the 6 core methods and 10+ practical cases in this article, developers can master the essence of time processing. From basic timestamp operations to complex timing task scheduling, the time module is always the most reliable partner. In actual development, it is recommended to choose appropriate methods based on specific scenarios, and pay attention to details such as time accuracy and system resource consumption.
The above is the detailed explanation of the common methods and applications of time modules in python. For more information about the methods and applications of python time modules, please pay attention to my other related articles!