You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改pytest-html生成的HTML报告文件名并添加动态时间戳?

解决pytest-html报告文件名重复覆盖问题(添加时间戳)

方法1:命令行直接生成带时间戳的文件名

根据不同操作系统,运行pytest时直接指定带时间戳的报告文件名即可:

Linux/macOS 终端

pytest --html=report_$(date +%Y%m%d_%H%M%S).html

Windows 命令提示符(CMD)

pytest --html=report_%date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%.html

Windows PowerShell

pytest --html="report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"

方法2:通过conftest.py自动配置动态文件名

如果不想每次手动输入命令行参数,可以在项目根目录的conftest.py中添加以下代码,自动为报告文件名添加时间戳:

import datetime
import os
import pytest

def pytest_addoption(parser):
    parser.addoption("--html", action="store", default=None, help="Generate HTML report")

def pytest_configure(config):
    html_path = config.getoption("--html")
    if html_path:
        # 生成时间戳
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        # 拆分路径和文件名,避免破坏原有目录结构
        dir_name, file_name = os.path.split(html_path)
        name, ext = os.path.splitext(file_name)
        # 构造带时间戳的新文件名
        new_file_name = f"{name}_{timestamp}{ext}"
        new_html_path = os.path.join(dir_name, new_file_name)
        # 更新配置中的报告路径
        config.option.htmlpath = new_html_path

使用时只需正常运行带--html参数的命令,比如:

pytest --html=report.html

程序会自动将文件名改为report_20240520_143022.html这类格式,避免重复覆盖。

补充说明

  • 时间戳格式可按需修改,比如%Y-%m-%d_%H-%M-%S会生成2024-05-20_14-30-22这种带分隔符的格式。
  • 若想强制生成带时间戳的报告(无需手动输入--html参数),可在pytest_configure中自动添加该参数并设置路径,具体逻辑可根据需求调整。

内容的提问来源于stack exchange,提问作者JD2775

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 19:43:27