From c8f92c0abe2d2e8868ecd82aa8ed1219595a4909 Mon Sep 17 00:00:00 2001 From: Evan Pratten Date: Thu, 21 Mar 2024 15:42:22 -0400 Subject: [PATCH] Add timestamp tool --- scripts/normalize-timestamp | 46 +++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100755 scripts/normalize-timestamp diff --git a/scripts/normalize-timestamp b/scripts/normalize-timestamp new file mode 100755 index 0000000..f70da3d --- /dev/null +++ b/scripts/normalize-timestamp @@ -0,0 +1,46 @@ +#! /usr/bin/env python3 + +import argparse +import sys +import logging +import subprocess +from pathlib import Path +from datetime import datetime + +logger = logging.getLogger(__name__) + +def main() -> int: + # Handle program arguments + ap = argparse.ArgumentParser(prog='normalize-timestamp', description='Normalizes timestamps on files') + ap.add_argument("--mode", help="Normalization mode", choices=["earliest", "latest"], default="earliest") + ap.add_argument('files', help='Files to normalize', nargs='+', type=Path) + ap.add_argument('-v', '--verbose', help='Enable verbose logging', action='store_true') + args = ap.parse_args() + + # Configure logging + logging.basicConfig( + level=logging.DEBUG if args.verbose else logging.INFO, + format='%(levelname)s: %(message)s', + ) + + # Iter files + for file in args.files: + + # Read the timestamps + creation_time = datetime.fromtimestamp(file.stat().st_ctime) + modification_time = datetime.fromtimestamp(file.stat().st_mtime) + + # Normalize the timestamps + if args.mode == "earliest": + new_time = min(creation_time, modification_time) + else: + new_time = max(creation_time, modification_time) + + # Set the new timestamps + logger.info(f"Setting {args.mode} timestamp on {file}") + subprocess.run(["touch", "-t", new_time.strftime("%Y%m%d%H%M.%S"), file]) + + return 0 + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file