How to Backup an SQLite Database with a Timestamp in Python

Backs up an SQLite database file to a timestamped copy using the sqlite3 backup API.

Easy Python 3.7+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

38 lines
Python 3.7+
import sqlite3
import shutil
from datetime import datetime
from pathlib import Path

def backup_database(db_path: str, backup_dir: str = "backups") -> Path:
    db = Path(db_path)
    backup_folder = Path(backup_dir)
    backup_folder.mkdir(exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_name = f"{db.stem}_{timestamp}.db"
    backup_path = backup_folder / backup_name
    
    # Create a proper backup using SQLite's backup API
    source = sqlite3.connect(db_path)
    destination = sqlite3.connect(backup_path)
    source.backup(destination)
    destination.close()
    source.close()
    
    return backup_path

if __name__ == "__main__":
    # Create a test database
    test_db = "example.db"
    conn = sqlite3.connect(test_db)
    conn.execute("CREATE TABLE users (id INTEGER, name TEXT)")
    conn.execute("INSERT INTO users VALUES (1, 'Alice')")
    conn.commit()
    conn.close()
    
    backup = backup_database(test_db)
    print(f"Backup created at: {backup}")
    
    # Clean up test files
    Path(test_db).unlink()
    backup.unlink()

Output

stdout
Backup created at: backups/example_20250315_123456.db

How it works

The sqlite3.Connection.backup method performs a safe online backup, copying the database while it may be in use. Using the backup API prevents file corruption that can occur with simple shutil.copy when the source database is being written to concurrently. The timestamp is generated with datetime.now().strftime("%Y%m%d_%H%M%S") to create a unique, sortable filename. The backup directory is created with mkdir(exist_ok=True) to avoid errors if it already exists. The function returns the Path to the backup file, making it easy to integrate into larger scripts.

Common mistakes

  • Using `shutil.copy` instead of the backup API, risking corruption if the database is being written to.
  • Forgetting to close connections, which can leave locks on the database files.
  • Not using `exist_ok=True` in `mkdir`, causing errors if the backup folder exists.

Variations

  1. Use `shutil.copy2` for a simple file copy if the database is not in active use.
  2. Compress the backup into a `.zip` or `.gz` archive to save space.

Real-world use cases

  • Scheduling a nightly backup of a production SQLite database to a separate directory.
  • Creating pre-deployment backup snapshots before running migrations or schema changes.
  • Automating backup generation for user data in a small desktop application.

Sponsored

Run this sample

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

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.