Here is another version that backup file before it’s being overwritten with new data and appends date/time of the last modification date of the original file (not current date of the backup)
i.e. file C:\blah\mycode.js will be backed up as D:\Backup\Notepad++\C\blah\mycode.js_20210928_221824.js
It also works with network shares
from os import makedirs
from os.path import split, splitext, exists, getmtime
from shutil import copyfile
from time import strftime, localtime
from re import sub
from Npp import *
def callback_FILEBEFORESAVE(args):
    backup_dir = "D:\\Backup\\Notepad++\\";             # backup directory, must have trailing slash
    _file = notepad.getBufferFilename(args['bufferID']) # get full path
    if not exists(_file):                               # new file?
        return
    with open(_file, "r") as f:                         # read data from file
      if f.read() == editor.getText():                  # only save if file was modified
        console.write(msg + "file unchanged, no backup created\n")
        return
    file = sub("^\\\\+", "",                            # remove \ at beginning of the path
           sub('[<>"|?*:]', "_",                        # just a precation, replace invalid characters with _
           sub("^([a-zA-Z]):", r"\1",                   # remove : after drive letter
           _file)))
    dir, file = split(file)                             # get directory and file
    filename, ext = splitext(file)                      # get filename and extension
    new_dir = backup_dir + dir + "\\";
    new_filename = filename + ext                       # original filename
    new_filename = new_filename + str(strftime("_%Y%m%d_%H%M%S", localtime(getmtime(_file)))) + ext; # append date/time and original extension
    if not exists(new_dir):
      try:
        makedirs(new_dir)
      except Exception as err:
        console.write(msg + str(err).replace("\\\\", "\\") + "\n")
        return
    try:
      copyfile(_file, new_dir + new_filename)
      console.write(msg + "saved as " + new_dir + new_filename + "\n")
    except Exception as err:
      console.write(msg + str(err).replace("\\\\", "\\") + "\n")
notepad.clearCallbacks([NOTIFICATION.FILEBEFORESAVE])
notepad.callback(callback_FILEBEFORESAVE, [NOTIFICATION.FILEBEFORESAVE])
msg = "[Auto backup] " # console message prefix
console.write(msg + "initialized\n")
For easy managing it’s better to save this script as a separate file i.e autobackup.py in the same directory where startup.py is
and at the end of startup.py add this line:
import autobackup # script's filename without extension