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.
Python code
13 linesfrom 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
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
- Use `time.time()` or `uuid.uuid4()` for random unique identifiers instead of timestamps
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.