To do this in Python is simpler than some of these other options, as os.utime
accepts the Unix timestamp output by the git log
command. This example uses GitPython but it'd also work with subprocess.run
to call git log
.
import gitfrom os import utimefrom pathlib import Pathrepo_path = "my_repo"repo = git.Repo(repo_path)for n in repo.tree().list_traverse(): filepath = Path(repo.working_dir) / n.path unixtime = repo.git.log("-1", "--format='%at'", "--", n.path ).strip("'") if not unixtime.isnumeric(): raise ValueError( f"git log gave non-numeric timestamp {unixtime} for {n.path}" ) utime(filepath, times=(int(unixtime), int(unixtime)))
This matches the results of the git restore-mtime
command in this answer and the script in the highest rated answer.
If you're doing this immediately after cloning, then you can reuse the to_path
parameter passed to git.Repo.clone_from
instead of accessing the working_dir
attribute on the Repo
object.