How to get creation and modification date/time of a file using Python?



To get the creation time of a file, you can use the os.path.getctime(file_path) on windows. On UNIX systems, you cant use the same function as it returns the last time that the file's attributes or content were changed. To get the creation time on UNIX based systems, use the st_birthtime attribute of the stat tuple.

 example

On Windows −

>>> import os
>>> print os.path.getctime('my_file')
1505928271.0689342

It gives the time in the number of seconds since the epoch. For UNIX systems,

import os
stat = os.stat(path_to_file)
try:
    print(stat.st_birthtime)
except AttributeError:
    # Probably on Linux. No easy way to get creation dates here,
    # so we'll settle for when its content was last modified.
    print(stat.st_mtime)

Output

This will give the output −

1505928271.0689342

For getting the modification time for a file, you can use the os.path.getmtime(path). It is supported cross-platform.For example,

>>> import os
>>> print os.path.getmtime('my_file')
1505928275.3081832

Advertisements