How to get file creation & modification date/times in Python?

前端 未结 13 2017
抹茶落季
抹茶落季 2020-11-21 11:44

I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.

13条回答
  •  青春惊慌失措
    2020-11-21 12:13

    You have a couple of choices. For one, you can use the os.path.getmtime and os.path.getctime functions:

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

    Your other option is to use os.stat:

    import os, time
    (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
    print("last modified: %s" % time.ctime(mtime))
    

    Note: ctime() does not refer to creation time on *nix systems, but rather the last time the inode data changed. (thanks to kojiro for making that fact more clear in the comments by providing a link to an interesting blog post)

提交回复
热议问题