python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python time模块

Python中内置模块time获取时间戳的完整教学

作者:星河耀银海

本文为大家详细介绍了Python内置模块time的核心功能,重点讲解了时间戳处理、程序暂停和性能计时三大应用场景,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下

一、开篇:time和datetime的分工

time模块和datetime模块经常让人困惑——它们有重叠的功能。简单来说:time模块更底层,处理Unix时间戳、程序暂停、性能计时;datetime模块更高级,面向日期时间的创建、计算和格式化。

快速区分:

import time
from datetime import datetime

# 获取"现在"的两种方式
ts = time.time()              # time模块:返回Unix时间戳(浮点数)
dt = datetime.now()           # datetime模块:返回datetime对象

print(f"time模块 → 时间戳: {ts}")
print(f"datetime模块 → datetime对象: {dt}")

# time模块的独特功能:
# - sleep() —— 暂停执行
# - perf_counter() —— 高精度性能计时
# - gmtime()/localtime() —— 结构化时间

二、时间戳:Unix纪 元的秒数

2.1 基本概念和操作

import time
# Unix纪 元:1970年1月1日 00:00:00 UTC
# 时间戳 = 从纪 元到现在的秒数
# 获取当前时间戳
now = time.time()
print(f"当前时间戳: {now}")
print(f"类型: {type(now)}")  # <class 'float'>
# 纳秒级时间戳(Python 3.7+)
now_ns = time.time_ns()
print(f"纳秒时间戳: {now_ns}")
# 时间戳转结构化时间
local = time.localtime(now)
utc = time.gmtime(now)
print(f"本地时间: {local.tm_year}-{local.tm_mon:02d}-{local.tm_mday:02d} "
      f"{local.tm_hour:02d}:{local.tm_min:02d}:{local.tm_sec:02d}")
print(f"UTC时间: {utc.tm_year}-{utc.tm_mon:02d}-{utc.tm_mday:02d} "
      f"{utc.tm_hour:02d}:{utc.tm_min:02d}:{utc.tm_sec:02d}")
# struct_time的属性
for attr in ['tm_year', 'tm_mon', 'tm_mday', 'tm_hour', 'tm_min',
             'tm_sec', 'tm_wday', 'tm_yday', 'tm_isdst']:
    print(f"  {attr} = {getattr(local, attr)}")

2.2 人类可读的时间格式

import time

# ctime() —— 最快速的人类可读格式
print(time.ctime())  # Sat Jun 15 14:30:00 2024

# 格式化时间
now = time.localtime()
print(time.strftime("%Y-%m-%d %H:%M:%S", now))
print(time.strftime("%A, %B %d, %Y", now))

# 解析时间字符串
time_str = "2024-06-15 14:30:00"
parsed = time.strptime(time_str, "%Y-%m-%d %H:%M:%S")
print(parsed)  # struct_time

# 转回时间戳
ts = time.mktime(parsed)
print(f"时间戳: {ts}")

# 💡 strftime/strptime的格式代码和datetime模块一致

三、sleep():暂停执行

import time

# sleep(seconds) —— 暂停程序执行

print("倒计时开始...")
for i in range(5, 0, -1):
    print(i)
    time.sleep(1)  # 暂停1秒
print("时间到!")

# 进度指示器
def progress_bar(total, width=50):
    """简单的进度条"""
    for i in range(total + 1):
        percent = i / total
        filled = int(width * percent)
        bar = "█" * filled + "░" * (width - filled)
        print(f"\r[{bar}] {percent * 100:.0f}%", end="", flush=True)
        time.sleep(0.05)
    print()

# progress_bar(100)

# sleep()接受浮点数
time.sleep(0.5)  # 暂停500毫秒

四、性能计时:测量代码执行时间

4.1 perf_counter()——高精度计时

import time

# perf_counter() —— 高精度性能计数器
# 包含sleep时间,适合测量墙钟时间(Wall-clock time)

# 测量代码执行时间
start = time.perf_counter()

# 模拟耗时操作
result = sum(range(10_000_000))

end = time.perf_counter()
elapsed = end - start
print(f"执行时间: {elapsed:.4f}秒")

# 创建计时器上下文管理器
class Timer:
    """上下文管理器——测量代码块执行时间"""
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, *args):
        self.end = time.perf_counter()
        self.elapsed = self.end - self.start
        print(f"⏱ 耗时: {self.elapsed:.6f}秒")

# 使用
with Timer():
    total = 0
    for i in range(1_000_000):
        total += i ** 2

4.2 函数执行时间装饰器

import time
from functools import wraps

def timing_decorator(func):
    """测量函数执行时间的装饰器"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"⏱ {func.__name__} 执行耗时: {elapsed:.6f}秒")
        return result
    return wrapper

@timing_decorator
def slow_calculation(n):
    """模拟慢计算"""
    return sum(i ** 2 for i in range(n))

@timing_decorator
def fast_calculation(n):
    """使用数学公式的快速计算"""
    return n * (n - 1) * (2 * n - 1) // 6

slow_calculation(1_000_000)
fast_calculation(1_000_000)

4.3 process_time()——CPU时间

import time

# process_time() —— 进程使用的CPU时间
# 不包含sleep时间,适合测量纯计算性能

def compare_timers():
    """对比perf_counter和process_time"""

    # perf_counter —— 包含sleep
    start = time.perf_counter()
    time.sleep(1)
    perf = time.perf_counter() - start

    # process_time —— 不包含sleep
    start = time.process_time()
    time.sleep(1)
    proc = time.process_time() - start

    print(f"perf_counter (含sleep): {perf:.2f}秒")
    print(f"process_time (不含sleep): {proc:.4f}秒")

compare_timers()

# 💡 使用建议:
# - 测量真实等待时间 → perf_counter()
# - 测量CPU计算时间 → process_time()
# - 测量代码优化效果 → perf_counter()(考虑多次取平均)

4.4 性能对比工具

import time

def benchmark(func, *args, runs=100, **kwargs):
    """简单的性能基准测试"""
    times = []
    for _ in range(runs):
        start = time.perf_counter()
        func(*args, **kwargs)
        times.append(time.perf_counter() - start)

    avg = sum(times) / len(times)
    min_time = min(times)
    max_time = max(times)

    print(f"{func.__name__}: 平均={avg*1000:.3f}ms, "
          f"最小={min_time*1000:.3f}ms, 最大={max_time*1000:.3f}ms "
          f"(运行{runs}次)")

# 对比两种实现
def method_1(n):
    """列表推导式"""
    return [x ** 2 for x in range(n)]

def method_2(n):
    """map+lambda"""
    return list(map(lambda x: x ** 2, range(n)))

benchmark(method_1, 100000)
benchmark(method_2, 100000)

五、总结

time模块和datetime模块各司其职。time管底层的时间戳、暂停和性能计时;datetime管高级的日期时间操作。

核心要点:

功能函数说明
获取时间戳time.time()Unix秒数
暂停time.sleep(s)暂停s秒
性能计时time.perf_counter()高精度墙钟时间
CPU时间time.process_time()进程CPU时间
结构化时间time.localtime()struct_time

性能测试用perf_counter(),日期操作交给datetime,暂停用sleep()。记住这个分工。

以上就是Python中内置模块time获取时间戳的完整教学的详细内容,更多关于Python time模块的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文