Python – 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?

Best Solution

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 os
import platform

def 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 for explanation.
    if platform.system() == 'Windows':
        return os.path.getctime(path_to_file)
        stat = os.stat(path_to_file)
            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