You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用GitPython获取指定文件的最后一次修改时间?

使用GitPython获取指定文件的最后一次修改日期

你当前拿到的Blob对象是文件内容的哈希引用,它本身不包含修改日期——同一个Blob可能出现在多个提交中,所以需要找到最后一次修改该文件的提交,再从提交中提取时间。

以下是两种可行方案:

方案一:纯GitPython API实现

遍历当前分支的提交(从新到旧),检查每个提交中该文件的状态,找到最后一次修改的提交:

import git
from datetime import datetime

repo = git.Repo()
file_path = 'path/to/a/file.py'
last_modified_commit = None

# 从最新提交开始遍历
for commit in repo.iter_commits(repo.active_branch):
    try:
        # 检查当前提交是否包含目标文件
        commit.tree[file_path]
        # 无父提交(初始提交)直接记录
        if not commit.parents:
            last_modified_commit = commit
            break
        # 对比与父提交的文件内容差异
        parent_tree = commit.parents[0].tree
        try:
            if commit.tree[file_path] != parent_tree[file_path]:
                last_modified_commit = commit
                break
        except KeyError:
            # 父提交无此文件,说明当前提交是新增文件
            last_modified_commit = commit
            break
    except KeyError:
        # 当前提交无此文件,继续往前找
        continue

# 转换提交时间为可读格式
if last_modified_commit:
    last_modified_date = datetime.fromtimestamp(last_modified_commit.committed_date)
    print(f"文件最后修改日期: {last_modified_date}")
else:
    print("仓库中未找到指定文件")

方案二:调用底层Git命令(更高效)

直接利用git log命令快速定位最后一次修改的提交,适合大仓库场景:

import git
from datetime import datetime

repo = git.Repo()
file_path = 'path/to/a/file.py'

# 执行git log命令,获取最后一次修改的提交时间戳(%ct为UNIX时间戳)
try:
    timestamp = repo.git.log('-1', '--format=%ct', file_path)
    last_modified_date = datetime.fromtimestamp(int(timestamp))
    print(f"文件最后修改日期: {last_modified_date}")
except git.GitCommandError:
    print("仓库中未找到指定文件")

方案对比

  • 方案一:纯Python API实现,无需依赖Git命令输出解析,但遍历提交效率较低,适合小型仓库。
  • 方案二:复用Git原生命令的优化逻辑,查询速度更快,适合大型仓库或需要频繁查询的场景。

内容的提问来源于stack exchange,提问作者Antoine Gallix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 16:54:57