time
time
库是 Python 标准库中的一部分,提供了与时间相关的功能,包括获取当前时间、时间格式化、时间延迟等。使用 time
库可以方便地处理时间相关的任务。
基本功能
获取当前时间戳
使用 time()
函数可以获取当前系统时间,返回自 1970 年 1 月 1 日零时以来的秒数(Unix 时间戳)。
import time
current_time = time.time()
print("Current time:", current_time)
性能计时
time.perf_counter()
、time.process_time()
和 time.process_time_ns()
是用于测量时间的函数,它们的作用和用法如下:
1. time.perf_counter()
time.perf_counter()
函数返回一个性能计数器的值,这个值以秒为单位,用于测量程序执行的时间,包括睡眠时间。它是一个递增的浮点数,不受系统时钟的影响。
import time
start = time.perf_counter()
# 执行一些操作
time.sleep(1)
end = time.perf_counter()
execution_time = end - start
print("Execution time:", execution_time, "seconds")
2. time.process_time()
time.process_time()
函数返回当前进程的 CPU 时间,以秒为单位。它仅包括该进程在 CPU 上执行代码的时间,不包括睡眠时间或其他进程的时间。
import time
start = time.process_time()
# 执行一些操作
time.sleep(1)
end = time.process_time()
execution_time = end - start
print("Execution time:", execution_time, "seconds")
3. time.process_time_ns()
time.process_time_ns()
函数类似于 time.process_time()
,但它返回的是纳秒(nanoseconds)级别的 CPU 时间,而不是秒。
import time
start = time.process_time_ns()
# 执行一些操作
time.sleep(1)
end = time.process_time_ns()
execution_time = (end - start) / 1e9 # 将纳秒转换为秒
print("Execution time:", execution_time, "seconds")
时间格式化
使用 ctime()
函数可以将时间戳格式化为可读的字符串表示。
formatted_time = time.ctime(current_time)
print("Formatted time:", formatted_time)
时间延迟
使用 sleep()
函数可以让程序休眠指定的秒数。
print("Start sleeping...")
time.sleep(3)
print("Wake up!")
时间元组
time
库中还定义了时间元组(struct_time),它是一个包含了年、月、日等时间信息的元组。常用的函数如下:
gmtime()
:获取当前的 UTC 时间。北京时间比这个时间早八小时。localtime()
:获取当前的本地时间。mktime()
:将时间元组转换为时间戳。strptime()
:将字符串转换为时间元组。
# 获取当前的 UTC 时间
utc_time_tuple = time.gmtime()
print("UTC time tuple:", utc_time_tuple)
# 获取当前的本地时间
local_time_tuple = time.localtime()
print("Local time tuple:", local_time_tuple)
# 将时间元组转换为时间戳
timestamp = time.mktime(local_time_tuple)
print("Timestamp:", timestamp)
时间格式化字符串
time
库中定义了一些常用的时间格式化字符串,用于将时间元组或时间戳格式化为指定的字符串。
%Y
:年份(4 位数)%m
:月份(01-12)%d
:日期(01-31)%H
:小时(00-23)%M
:分钟(00-59)%S
:秒(00-59)
formatted_local_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time_tuple)
print("Formatted local time:", formatted_local_time)
性能计时
time
库也可以用于性能计时,以评估程序的执行时间。
start_time = time.time()
# 执行一些耗时操作
time.sleep(2)
end_time = time.time()
execution_time = end_time - start_time
print("Execution time:", execution_time, "seconds")
random
Python的random
模块提供了生成伪随机数的工具。这些工具包括生成各种分布(如均匀、正态等)的随机数、随机选择元素、打乱序列等功能。这个模块是基于Mersenne Twister算法实现的,它是一个非常快速的伪随机数生成器,其周期长度达到2的19937次方减1。
基本使用
导入模块
在使用random
模块之前,需要先导入它:
import random
生成随机数
- 生成0到1之间的随机浮点数:
n = random.random()
print(n)
- 生成指定范围的随机整数:
n = random.randint(a, b) # 包括两端的a和b
print(n)
- 生成指定范围内的随机浮点数:
n = random.uniform(a, b) # 包括a,不一定包括b
print(n)