How to Build a Dated Backup Filename with Timestamp in Python

Generate unique backup filenames with a timestamp using Python's datetime module and f-strings.

Easy Python 3.6+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

13 lines
Python 3.6+
from datetime import datetime

def build_backup_filename(base_name: str, extension: str = "bak") -> str:
    """Generate a dated backup filename with timestamp."""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    return f"{base_name}_{timestamp}.{extension}"

if __name__ == "__main__":
    backup_file = build_backup_filename("database", "sql")
    print(backup_file)

    backup_file2 = build_backup_filename("config")
    print(backup_file2)

Output

stdout
database_20250321_143015.sql
config_20250321_143015.bak

How it works

This function combines the base filename with a timestamp in YYYYMMDD_HHMMSS format using datetime.now().strftime(). The resulting string is built with an f-string, which is both readable and efficient. Using the timestamp ensures each backup filename is unique, preventing accidental overwrites. The function also provides a default extension of 'bak', making it flexible for various file types.

Common mistakes

  • Forgetting to import datetime or using `datetime.date` instead of `datetime.datetime`
  • Not using zero-padding in the format string, leading to ambiguous filenames
  • Hardcoding the timestamp format instead of making it configurable

Variations

  1. Use `time.time()` or `uuid.uuid4()` for random unique identifiers instead of timestamps
  2. Add the timestamp as a suffix before the extension using `os.path.splitext` for existing file paths

Real-world use cases

  • Creating scheduled database backups that don't overwrite previous versions.
  • Generating unique log file names for each application run in production.
  • Versioning configuration files before applying changes in a deployment script.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.