Python中的时间函数:time()、sleep()、strftime()
在Python中,时间函数play a crucial role in managing time-related tasks and operations. Let's take a closer look at three important time functions in Python: time(), sleep(), and strftime().
1. time(): The time() function is used to retrieve the current system time, measured in seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). This function is often used to measure the execution time of the code or to generate a timestamp. Here's an example:
import time current_time = time.time() print(current_time)
Output:
1614323567.860561
The time() function returns the current timestamp as a floating-point number, which is useful for calculating time differences and performing other time-related calculations.
2. sleep(): The sleep() function is used to introduce a delay in the execution of the program. It temporarily suspends the execution for a specified number of seconds, allowing other processes or threads to run. This function is handy for adding delays or implementing time-based scheduling in Python. Here's an example:
import time
print("Start")
time.sleep(5)
print("End")
Output:
Start [5-second delay] End
In this example, the program pauses for 5 seconds before printing "End."
3. strftime(): The strftime() function is used to format a timestamp into a readable string representation. It takes a timestamp as an argument and returns a formatted string based on the specified format codes. Here's an example:
import time
current_time = time.time()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(current_time))
print(formatted_time)
Output:
2021-02-26 15:46:07
In this example, the current timestamp is formatted as "YYYY-MM-DD HH:MM:SS" using the strftime() function.
The strftime() function allows various format codes to represent different components of the timestamp, such as year (%Y), month (%m), day (%d), hour (%H), minute (%M), and second (%S), among others.
In conclusion, the time(), sleep(), and strftime() functions are essential in Python for managing time-related tasks. The time() function retrieves the current system time, the sleep() function introduces a delay, and the strftime() function formats timestamps into readable strings. These functions empower developers to handle various time-based operations efficiently.
