【问题标题】:Is there a way to get the year a file was created with python? [duplicate]有没有办法获取使用 python 创建文件的年份? [复制]
【发布时间】:2015-09-10 16:12:57
【问题描述】:

标题说明了一切。我正在尝试获取为索引目的创建文件的年份。另外,如果这很重要,我会在 Windows 上。

【问题讨论】:

    标签: python


    【解决方案1】:

    这个问题已经有人问过了,这里简单说一下,看下面的代码:

    import os.path, time
    print "last modified: %s" % time.ctime(os.path.getmtime(file))
    print "created: %s" % time.ctime(os.path.getctime(file))
    

    这里是链接: How to get file creation & modification date/times in Python?

    【讨论】:

    • 不,这不是正确的解决方案,因为 getctime 正在返回最后的更改时间。而不是创建时间
    【解决方案2】:

    说实话,也有类似的问题,例如here

    os.stat 是你的朋友。它提供文件的各种统计信息。使用 ctime 将其更改为人类可读的内容,如演示 here

    import os.path, time
    when = os.stat(r"path").st_ctime
    time.ctime(when)
    

    【讨论】:

      【解决方案3】:

      所以这是解决方案:

      import os
      import datetime
      
      #gives the create time as a unix timestamp
      create_time = os.stat(<path to file>).st_ctime
      
      #returns a datetime object
      create_datetime = datetime.datetime.fromtimestamp(create_time)
      
      #print the year
      create_datetime.strftime("%Y")
      

      【讨论】:

      • 不,这不是正确的解决方案,因为 st_ctime 正在返回最后的更改时间。而不是创建时间
      • @RuchirShukla 这就是文档定义它的作用,在 unix 系统上 - docs.python.org/2/library/stat.html#stat.ST_CTIME
      • 这正是我要说的。“在某些系统(如 Unix)上是最后一次元数据更改的时间,而在其他系统(如 Windows)上,是创建时间(参见平台文档详细信息)。”
      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2019-02-11
      相关资源
      最近更新 更多