QA Graphic

In Pytest, what is the Best Date/Time Format for Filenames

Basic Filename Format to find Files

The best date/time format for filenames is ISO 8601 with modifications to ensure compatibility and readability. I recommend using YYYYMMDD_HHMMSS (e.g., 20250430_143022) for the following reasons:

  • Sortability: ISO 8601 (year-month-day) ensures files sort chronologically when listed.
  • Uniqueness: Including seconds prevents filename collisions during rapid test runs.
  • Readability: The format is clear and universally understood.
  • Filesystem Safety: Replacing colons (:) with underscores (_) avoids issues on filesystems that don't allow colons in filenames.

Here's an example of generating a timestamped filename in pytest:

Python
import pytest
from datetime import datetime
def get_timestamped_filename(base_name, extension):
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    return f"{base_name}_{timestamp}.{extension}"
# Example usage in a test
def test_example():
    filename = get_timestamped_filename("screenshot", "png")
    # Save screenshot with filename like "screenshot_20250430_143022.png"
    print(f"Saving screenshot as {filename}")

Tip: If you need microseconds for high-frequency tests, use datetime.now().strftime("%Y%m%d_%H%M%S_%f") to include microseconds (e.g., 20250430_143022_123456).

Alternative: For human-readable logs, you might include a readable date in the file content but keep the filename simple and sortable. For example, save a log with a header like Test Run: April 30, 2025 14:30:22 inside the file, but name the file log_20250430_143022.txt.

 

Comments

Add Your Comments

Name:
Comment:

 

About

Welcome to Pytest Tips and Tricks, your go-to resource for mastering the art of testing with Pytest! Whether you're a seasoned developer or just dipping your toes into the world of Python testing, this blog is designed to help you unlock the full potential of Pytest - one of the most powerful and flexible testing frameworks out there. Here, I'll share a treasure trove of practical insights, clever techniques, and time-saving shortcuts that I've gathered from years of writing tests and debugging code.

Schedule

Monday 12 Media
Tuesday 13 QA
Wednesday 14 Pytest
Thursday 15 PlayWright
Friday 16 Macintosh
Saturday 17 Internet Tools
Sunday 18 Misc