Python
file naming
datetime
programming
tutorial

How to create a file name with the current date time in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Creating a file name with the current date and time is a common Python pattern for logs, exports, backups, and generated reports. The usual solution is to get the current time with datetime.now() and format it with strftime() into a string that is readable, sortable, and safe for use in filenames.

The Basic Pattern

A straightforward example looks like this:

python
1from datetime import datetime
2
3timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
4filename = f"report_{timestamp}.txt"
5
6print(filename)

Typical output:

text
report_2026-03-07_14-32-05.txt

This works well because the name is easy to read, sorts naturally by time, and avoids awkward punctuation such as colons.

Why strftime() Is the Right Tool

strftime() lets you control the exact shape of the timestamp. Common format codes include:

  • '%Y for the four-digit year'
  • '%m for the month'
  • '%d for the day'
  • '%H for the hour'
  • '%M for the minute'
  • '%S for the second'

For a more compact file name, you can remove the dashes:

python
1from datetime import datetime
2
3stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
4filename = f"backup_{stamp}.zip"
5print(filename)

This produces names such as:

text
backup_20260307_143205.zip

The nice property of this layout is that lexical sort order also matches chronological order.

Avoid Unsafe Filename Characters

A common beginner mistake is to format the timestamp the way it would look on screen and then reuse it directly as a filename:

python
1from datetime import datetime
2
3bad_name = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
4print(bad_name)

That prints fine, but the colon characters are a poor choice in actual filenames on some operating systems. For filenames, separators such as _ and - are much safer, which is why %H-%M-%S is usually better than %H:%M:%S.

Create the File Directly

Here is a complete example that generates the name and writes a file using pathlib:

python
1from datetime import datetime
2from pathlib import Path
3
4timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
5path = Path(f"log_{timestamp}.txt")
6
7path.write_text("Job completed successfully\n", encoding="utf-8")
8print(path)

This is a clean pattern for scripts that produce logs, snapshots, or output reports.

Add More Precision When Needed

If the code can create more than one file in the same second, second-level precision may not be enough. Add microseconds with %f:

python
1from datetime import datetime
2
3timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S_%f")
4filename = f"snapshot_{timestamp}.json"
5print(filename)

That makes collisions much less likely in fast loops or concurrent tasks.

Use UTC for Cross-System Consistency

If filenames are generated on different machines or in different time zones, UTC is often more predictable than local time:

python
1from datetime import datetime, timezone
2
3timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d_%H-%M-%S_UTC")
4filename = f"backup_{timestamp}.zip"
5print(filename)

This makes the timezone explicit and avoids later confusion about what the timestamp really means.

A Reusable Helper Function

If timestamped filenames appear often in your project, wrap the pattern in a helper:

python
1from datetime import datetime
2
3
4def timestamped_filename(prefix: str, suffix: str) -> str:
5    stamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
6    return f"{prefix}_{stamp}{suffix}"
7
8
9print(timestamped_filename("report", ".csv"))
10print(timestamped_filename("backup", ".zip"))

This keeps naming consistent across the codebase.

Combine with a Directory Path

It is common to create the timestamped name inside an output directory:

python
1from datetime import datetime
2from pathlib import Path
3
4output_dir = Path("exports")
5output_dir.mkdir(exist_ok=True)
6
7stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
8path = output_dir / f"data_{stamp}.csv"
9
10print(path)

This pattern is especially useful for scheduled jobs and data exports.

Common Pitfalls

The biggest pitfall is using characters such as : in the filename because they look natural in timestamps. They are fine for display, but not a good universal choice for filesystem names.

Another pitfall is assuming second-level precision is always enough. If your program writes files very quickly, add %f for microseconds.

A third pitfall is using local time when the files need to be compared across systems in different regions. In those cases, UTC is often clearer.

Finally, avoid overengineering the format. A filename that is readable and sorts well is usually better than a clever but cryptic naming scheme.

Summary

  • Use datetime.now().strftime(...) to generate timestamped filenames in Python
  • Prefer filename-safe separators such as _ and -
  • Add microseconds if same-second collisions are possible
  • Use UTC when timestamps must stay consistent across systems
  • Wrap the pattern in a helper when your project creates timestamped files regularly

Course illustration
Course illustration

All Rights Reserved.