Mark Biek Mark Biek - 2 months ago 84
Python Question

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

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

What's the best cross-platform way to get file creation & modification date/times in Python?

Answer

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)

Comments