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
:
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
.