time
Python 的 time
模块提供了与时间相关的功能,主要用于获取系统时间、处理时间延迟和时间格式化。以下是对 time
模块的详细介绍,包括其主要功能和常用方法。对于更复杂的日期和时间操作,建议结合使用 datetime
模块。
主要功能
获取当前时间
time.time()
: 返回当前时间的时间戳(自1970年1月1日以来的秒数)。
pythonimport time current_time = time.time() print(current_time) # 输出当前时间戳
1
2
3
4时间格式化
time.strftime(format, t)
: 将时间元组t
格式化为字符串。t
可以是time.localtime()
或time.gmtime()
的返回值。time.strptime(string, format)
: 将字符串解析为时间元组。
pythonlocal_time = time.localtime() formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time) print(formatted_time) # 输出格式化的当前时间
1
2
3时间延迟
time.sleep(seconds)
: 暂停程序执行指定的秒数。
pythonprint("Start") time.sleep(2) # 暂停2秒 print("End") # 2秒后输出
1
2
3获取时间元组
time.localtime([seconds])
: 返回当前本地时间的时间元组,如果提供seconds
,则返回对应的本地时间。time.gmtime([seconds])
: 返回当前 UTC 时间的时间元组。
pythonlocal_time_tuple = time.localtime() print(local_time_tuple) # 输出时间元组
1
2获取时间戳
time.mktime(t)
: 将时间元组t
转换为时间戳。
pythontime_tuple = (2024, 7, 26, 12, 0, 0, 0, 0, 0) # 年、月、日、时、分、秒、周几、年第几天、夏令时 timestamp = time.mktime(time_tuple) print(timestamp) # 输出时间戳
1
2
3
常用示例
计算代码执行时间
可以使用 time.time()
来计算代码块的执行时间。
python
start_time = time.time()
# 执行一些操作
time.sleep(3) # 模拟耗时操作
end_time = time.time()
execution_time = end_time - start_time
print(f"Execution time: {execution_time} seconds")
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
时区处理
虽然 time
模块本身不直接支持时区,但可以使用 time.gmtime()
和 time.localtime()
来处理 UTC 和本地时间。
python
utc_time = time.gmtime()
print("UTC Time:", time.strftime("%Y-%m-%d %H:%M:%S", utc_time))
local_time = time.localtime()
print("Local Time:", time.strftime("%Y-%m-%d %H:%M:%S", local_time))
1
2
3
4
5
2
3
4
5