Python中的time模块使用方法及示例
发布时间:2023-06-30 05:14:41
time模块是Python的标准库之一,用于时间相关的操作。这里将介绍time模块的常用方法及示例。
1. time():返回当前的时间戳,即从1970年1月1日00:00:00经过的秒数。
示例:
import time current_time = time.time() print(current_time)
2. sleep():使程序暂停指定的秒数。
示例:
import time
print("开始操作")
time.sleep(5) # 暂停5秒
print("结束操作")
3. localtime():返回当前的时间,以struct_time对象的形式表示。
示例:
import time current_time = time.localtime() print(current_time)
4. strftime():根据指定的格式化字符串,格式化时间。
示例:
import time
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(current_time)
5. strptime():将字符串解析成时间对象。
示例:
import time time_str = "2021-07-01 12:00:00" time_obj = time.strptime(time_str, "%Y-%m-%d %H:%M:%S") print(time_obj)
6. mktime():将struct_time对象转换为时间戳。
示例:
import time
time_obj = time.strptime("2021-07-01 12:00:00", "%Y-%m-%d %H:%M:%S")
time_stamp = time.mktime(time_obj)
print(time_stamp)
7. perf_counter():返回程序运行的时间,以秒为单位,精度较高。
示例:
import time
start_time = time.perf_counter()
# 执行一些操作
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print("程序运行时间:", elapsed_time, "秒")
8. process_time():返回当前进程的CPU时间,以秒为单位。
示例:
import time
start_time = time.process_time()
# 执行一些操作
end_time = time.process_time()
elapsed_time = end_time - start_time
print("程序运行时间:", elapsed_time, "秒")
以上是time模块的一些常用方法及示例。请根据需要选择合适的方法来处理时间相关的操作。
