Python中的time模块提供了各种与时间相关的函数。这些函数允许你获取当前时间、测量执行时间、进行时间转换等。以下是一些time模块中常用的函数及其用途:
获取当前时间
- time(): 返回当前时间的UNIX时间戳(从1970年1月1日00:00:00 UTC到现在的秒数,包括小数部分表示微秒)。
import time
current_time = time.time()
print(current_time)
转换时间戳为可读格式
- ctime(): 将UNIX时间戳转换为可读的字符串形式。
- localtime(): 将UNIX时间戳转换为一个time.struct_time对象,表示本地时间。
- gmtime(): 将UNIX时间戳转换为一个time.struct_time对象,表示UTC时间。
import time
timestamp = time.time()
readable_time = time.ctime(timestamp)
local_struct_time = time.localtime(timestamp)
utc_struct_time = time.gmtime(timestamp)
print(readable_time)
print(local_struct_time)
print(utc_struct_time)
格式化时间
- strftime(): 使用指定的格式将time.struct_time对象转换为字符串。
import time
struct_time = time.localtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
print(formatted_time)
解析时间字符串
- strptime(): 将时间字符串解析为time.struct_time对象。
import time
time_string = "2023-03-15 12:34:56"
struct_time = time.strptime(time_string, "%Y-%m-%d %H:%M:%S")
print(struct_time)
睡眠和等待
- sleep(): 使程序暂停指定的秒数。
import time
print("Starting...")
time.sleep(5) # 暂停5秒
print("5 seconds later...")
性能测量
- perf_counter(): 返回一个性能计数器,用于测量短时间间隔。它通常比time()更准确。
- process_time(): 返回当前进程的系统和用户CPU时间总和。
import time
start = time.perf_counter()
# 执行一些代码...
end = time.perf_counter()
elapsed_time = end - start
print(f"Elapsed time: {elapsed_time:.6f} seconds")
这只是time模块提供功能的一部分。你可以通过查阅Python官方文档来了解更多关于time模块的信息和使用方法。time模块在处理与时间相关的任务时非常有用,但如果你需要更复杂的日期和时间处理功能,可能还需要结合使用datetime模块。