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

使用PyGithub获取GitHub仓库更新时间异常,求可行解决方案

解决思路与方案

1. 先搞懂GitHub仓库updated_at的更新逻辑

GitHub仓库的updated_at字段不会实时对应文件修改时间,它的更新只触发在这些场景:

  • 修改仓库设置(比如改描述、加协作者)
  • 往分支推送代码(尤其是默认分支)
  • 创建/删除标签、发布版本
  • 发起或合并PR

如果只是修改了仓库文件但没推送到远程,或者推送的是非默认分支,updated_at不会立刻变化。

2. 无需遍历文件的替代方案

方案一:用pushed_at字段获取最后推送时间

仓库的pushed_at会记录最后一次往任何分支推送代码的时间,更贴近你需要的文件更新时间。修改代码如下:

def access_project(title: str) -> dict:
    auth = Auth.Token(os.environ.get("GITHUB_TOKEN"))
    g = Github(auth=auth)
    repo = g.get_user().get_repo(title)
    my_project = {
        'title': title,
        'description': repo.description,
        # 替换为pushed_at,直接返回datetime对象
        'last_updated': repo.pushed_at,
    }
    print(repo.pushed_at)
    g.close()
    return my_project

方案二:获取默认分支的最新提交时间

如果要更精准的代码修改时间,可以直接取默认分支的最新commit时间:

def access_project(title: str) -> dict:
    auth = Auth.Token(os.environ.get("GITHUB_TOKEN"))
    g = Github(auth=auth)
    repo = g.get_user().get_repo(title)
    # 获取默认分支的最新提交记录
    latest_commit = repo.get_branch(repo.default_branch).commit
    my_project = {
        'title': title,
        'description': repo.description,
        'last_updated': latest_commit.commit.author.date,
    }
    print(latest_commit.commit.author.date)
    g.close()
    return my_project

3. 别用私有属性_updated_at

_updated_at是PyGithub的内部私有属性(以下划线开头),官方不建议直接调用,正确的公开属性是repo.updated_at,直接返回datetime对象,不需要取.value。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:32:41