Skip to content

Commit 3f81c5e

Browse files
committed
feat(new): add chrono_rename.py
1 parent 38aec35 commit 3f81c5e

1 file changed

Lines changed: 101 additions & 0 deletions

File tree

‎chrono_rename.py‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
__author__ = "ipetrash"
5+
6+
7+
import argparse
8+
9+
from datetime import datetime
10+
from pathlib import Path
11+
from typing import Final
12+
13+
DEFAULT_PATTERN: Final[str] = "{prefix}{datetime_fmt}{postfix}{suffix}"
14+
DEFAULT_PREFIX: Final[str] = ""
15+
DEFAULT_POSTFIX: Final[str] = ""
16+
DEFAULT_DATETIME_FMT: Final[str] = "%Y-%m-%d_%H-%M-%S-%f"
17+
18+
19+
def process(
20+
dir_path: Path,
21+
pattern: str = DEFAULT_PATTERN,
22+
prefix: str = DEFAULT_PREFIX,
23+
postfix: str = DEFAULT_POSTFIX,
24+
datetime_fmt: str = DEFAULT_DATETIME_FMT,
25+
) -> None:
26+
print("Processing parameters:")
27+
print(f" Directory: {dir_path}")
28+
print(f" Pattern: {pattern!r}")
29+
print(f" Prefix: {prefix!r}")
30+
print(f" Postfix: {postfix!r}")
31+
print(f" Format: {datetime_fmt!r}")
32+
print("-" * 40)
33+
print()
34+
35+
for path in dir_path.rglob("*.*"):
36+
if not path.is_file():
37+
continue
38+
39+
mtime_timestamp = path.stat().st_mtime
40+
mtime: datetime = datetime.fromtimestamp(mtime_timestamp)
41+
42+
new_name: str = pattern.format(
43+
prefix=prefix,
44+
datetime_fmt=mtime.strftime(datetime_fmt),
45+
postfix=postfix,
46+
suffix=path.suffix,
47+
)
48+
49+
new_path: Path = path.parent / new_name
50+
if path.name == new_path.name:
51+
continue
52+
53+
print(f'Renaming "{path}" to "{new_path.name}"')
54+
path.rename(new_path)
55+
56+
57+
if __name__ == "__main__":
58+
parser = argparse.ArgumentParser(
59+
description="Rename files based on their modification date and time.",
60+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
61+
)
62+
parser.add_argument(
63+
"dir_path",
64+
type=Path,
65+
help="Path to the target directory",
66+
)
67+
parser.add_argument(
68+
"--pattern",
69+
type=str,
70+
default=DEFAULT_PATTERN,
71+
help="Filename pattern template",
72+
)
73+
parser.add_argument(
74+
"--prefix",
75+
type=str,
76+
default=DEFAULT_PREFIX,
77+
help="Prefix to add before the date",
78+
)
79+
parser.add_argument(
80+
"--postfix",
81+
type=str,
82+
default=DEFAULT_POSTFIX,
83+
help="Postfix to add after the date",
84+
)
85+
parser.add_argument(
86+
"--fmt",
87+
dest="datetime_fmt",
88+
type=str,
89+
default=DEFAULT_DATETIME_FMT,
90+
help="Date and time format string",
91+
)
92+
93+
args = parser.parse_args()
94+
95+
process(
96+
dir_path=args.dir_path,
97+
pattern=args.pattern,
98+
prefix=args.prefix,
99+
postfix=args.postfix,
100+
datetime_fmt=args.datetime_fmt,
101+
)

0 commit comments

Comments
 (0)