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

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


Getting some sort of modification date in a cross-platform way is easy - just call os.path.getmtime(path) and you'll get the Unix timestamp of when the file at path was last modified.

Getting file creation dates, on the other hand, is fiddly and platform-dependent, differing even between the three big OSes:

Putting this all together, cross-platform code should look something like this...

import osimport platformdef creation_date(path_to_file):    """    Try to get the date that a file was created, falling back to when it was    last modified if that isn't possible.    See http://stackoverflow.com/a/39501288/1709587 for explanation.    """    if platform.system() == 'Windows':        return os.path.getctime(path_to_file)    else:        stat = os.stat(path_to_file)        try:            return stat.st_birthtime        except AttributeError:            # We're probably on Linux. No easy way to get creation dates here,            # so we'll settle for when its content was last modified.            return stat.st_mtime


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

import os.path, timeprint("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)


The best function to use for this is os.path.getmtime(). Internally, this just uses os.stat(filename).st_mtime.

The datetime module is the best manipulating timestamps, so you can get the modification date as a datetime object like this:

import osimport datetimedef modification_date(filename):    t = os.path.getmtime(filename)    return datetime.datetime.fromtimestamp(t)

Usage example:

>>> d = modification_date('/var/log/syslog')>>> print d2009-10-06 10:50:01>>> print repr(d)datetime.datetime(2009, 10, 6, 10, 50, 1)