How to Add Dynamic Names to PyAutoGUI Screenshots
Create timestamped, collision-resistant PyAutoGUI screenshot filenames, save them safely, and troubleshoot common capture errors.

Generate the filename before calling pyautogui.screenshot(), then pass that filename to the function. Python’s datetime formatting gives each image a readable date and time:
from datetime import datetime
import pyautogui
filename = f"screenshot_{datetime.now():%Y%m%d_%H%M%S}.png"
pyautogui.screenshot(filename)
A capture made on September 29, 2026 at 20:13:11 would be saved as screenshot_20260929_201311.png. PyAutoGUI documents that screenshot() accepts a filename and returns the captured image object. See the official screenshot documentation and quickstart.
1. Add a timestamp to every screenshot
The format string controls the filename:

| Code | Meaning | Example |
|---|---|---|
%Y |
Four-digit year | 2026 |
%m |
Two-digit month | 09 |
%d |
Two-digit day | 29 |
%H |
Hour in 24-hour time | 20 |
%M |
Minute | 13 |
%S |
Second | 11 |
%f |
Microseconds | 201311 |
For captures that can occur within the same second, include microseconds:
from datetime import datetime
import pyautogui
filename = f"screenshot_{datetime.now():%Y%m%d_%H%M%S_%f}.png"
pyautogui.screenshot(filename)
Second-level timestamps are easy to read but can collide when two calls run close together. Microseconds reduce that practical risk. They are a naming technique, not a uniqueness guarantee; a counter or UUID is appropriate when uniqueness must be enforced.
2. Include a scenario or test name
A label makes a directory of captures easier to search:
from datetime import datetime
import pyautogui
scenario = "login_test"
filename = f"{scenario}_{datetime.now():%Y%m%d_%H%M%S_%f}.png"
pyautogui.screenshot(filename)
Use labels such as checkout_error, dashboard_dark_mode, or step_03. If a label comes from a user, URL, or test case, sanitize it before using it as a path component. Replace characters that are invalid on the target operating system, remove path separators, and consider limiting its length.
Use a counter when ordering matters
from datetime import datetime
from itertools import count
import pyautogui
sequence = count(1)
for action in ("open", "fill", "submit"):
number = next(sequence)
filename = f"{number:03d}_{action}_{datetime.now():%Y%m%d_%H%M%S_%f}.png"
pyautogui.screenshot(filename)
The counter preserves the order within one process. Keep the timestamp as context, and use a UUID or a database-backed identifier if several processes write to the same directory.
3. Save screenshots in a dedicated folder
Create the destination directory before capture and pass the complete path to PyAutoGUI:
from datetime import datetime
from pathlib import Path
import pyautogui
output_dir = Path("screenshots")
output_dir.mkdir(parents=True, exist_ok=True)
filename = f"capture_{datetime.now():%Y%m%d_%H%M%S_%f}.png"
path = output_dir / filename
pyautogui.screenshot(str(path))
print(f"Saved {path}")
Path handles path separators for the current operating system. Convert it to str for broad compatibility with library versions.
4. Keep the returned image for further processing
pyautogui.screenshot(path) both saves the file and returns an image object. If you need to crop, inspect, annotate, or otherwise manipulate it, retain the return value:
from datetime import datetime
from pathlib import Path
import pyautogui
output_dir = Path("screenshots")
output_dir.mkdir(exist_ok=True)
filename = f"processed_{datetime.now():%Y%m%d_%H%M%S_%f}.png"
path = output_dir / filename
image = pyautogui.screenshot()
# Perform Pillow operations here, for example: image = image.crop((0, 0, 800, 600))
image.save(path)
The direct filename form is simplest when no image processing is needed. Calling save() yourself is useful when the image must be transformed first or when the final format and destination are selected later.
5. Choose an output format and extension
PyAutoGUI’s screenshot result is a Pillow image. The extension you use when saving determines the format in the normal Pillow workflow:
from datetime import datetime
from pathlib import Path
import pyautogui
stamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
image = pyautogui.screenshot()
image.save(Path("screenshots") / f"capture_{stamp}.png")
image.save(Path("screenshots") / f"capture_{stamp}.jpg", quality=90)
PNG is lossless and suitable for UI text. JPEG is smaller but introduces compression artifacts. Ensure the destination directory exists before calling save().
6. Avoid overwriting existing files
Timestamped names normally avoid overwrites, but a second-level timestamp can repeat. You can check and increment a suffix:
from datetime import datetime
from pathlib import Path
import pyautogui
output_dir = Path("screenshots")
output_dir.mkdir(parents=True, exist_ok=True)
base = datetime.now().strftime("capture_%Y%m%d_%H%M%S")
path = output_dir / f"{base}.png"
counter = 1
while path.exists():
path = output_dir / f"{base}_{counter}.png"
counter += 1
pyautogui.screenshot(str(path))
This check is appropriate for a single process. For concurrent writers, use an atomic file-creation strategy or generate a UUID and treat collisions as errors.
7. Dependencies and platform setup
- Install PyAutoGUI with
python -m pip install pyautogui. - Screenshot support requires Pillow.
- On Linux, PyAutoGUI’s documentation identifies
scrotas a required screenshot dependency; install it using your distribution’s package manager. - On macOS, the documentation mentions the system
screencapturecommand. - Run the script in a desktop session with permission to capture the screen. Headless CI environments need a virtual display or a browser-based capture approach.
Check the current platform instructions when an operating-system package is missing.
8. Performance and reliability considerations
PyAutoGUI’s documentation gives roughly 100 milliseconds as an example for a 1920 × 1080 capture. Treat that as an approximate documentation figure, not a benchmark or promise for your machine. Large displays, remote desktops, compositing, disk speed, and image encoding can change the time.
- Capture only when the UI has reached the expected state; add an explicit wait in your automation rather than relying on a filename timestamp.
- Use microseconds or a sequence number when taking bursts of screenshots.
- Write to local storage first when latency matters, then upload or archive asynchronously.
- Clean old captures with a retention policy so an automated run does not fill the disk.
- For reproducible tests, include the test name, step number, and run identifier in the filename.
9. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
ImportError: No module named PIL |
Pillow is not installed in the active environment. | Install it with python -m pip install pillow, then rerun the script. |
| Linux screenshot backend error | The required scrot package is missing or unavailable. |
Install scrot using the Linux distribution’s package manager and verify it is on PATH. |
FileNotFoundError for the output path |
The destination directory does not exist. | Call mkdir(parents=True, exist_ok=True) before capture. |
| Files overwrite one another | The name contains only seconds and captures happen within one second. | Add %f, a counter, or a UUID. |
| Invalid filename or permission denied | The label contains OS-reserved characters, or the process cannot write to the directory. | Sanitize labels and choose a writable folder. |
| Black, empty, or unexpected image | The desktop session, window state, display permissions, or timing is wrong. | Confirm a visible desktop session, wait for the target UI, and test a manual capture in the same environment. |
| Works locally but fails in CI | CI is headless or lacks screenshot dependencies. | Use a configured virtual display for desktop capture, or use a browser screenshot API for web pages. |
10. Or skip the browser setup
If what you actually need is a screenshot of a web page rather than the physical desktop, ScreenshotNeo provides a single HTTP request. It removes cookie and consent banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and each response reports the result in X-Page-Verdict and X-Billed headers. Its MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf.

See the ScreenshotNeo API documentation for all options.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
ScreenshotNeo has 1,000 free screenshots each month with no card. Paid plans start at $5 for 3,000 screenshots, and every feature is available on every plan. Create a free ScreenshotNeo account.
11. FAQ
Can I use a human-readable date in the filename?
Yes, but sortable numeric formats such as %Y%m%d_%H%M%S keep files in chronological order when listed alphabetically.
Does PyAutoGUI create the output directory?
No. Create it with Path.mkdir(..., exist_ok=True) or another standard-library method before saving.
Should I call screenshot(filename) or image.save(filename)?
Pass the filename directly for a straightforward save. Capture first and call save() when you need to process or choose the output format afterward.
Are timestamps guaranteed to be unique?
No. Add microseconds, a counter, or a UUID when collisions would be harmful, and use an atomic strategy when multiple processes write concurrently.


