How do I get the time a file was last modified in Python?

PythonFileTime

Python Problem Overview


Assuming the file exists (using os.path.exists(filename) to first make sure that it does), how do I display the time a file was last modified? This is on Linux if that makes any difference.

Python Solutions


Solution 1 - Python

>>> import os
>>> f = os.path.getmtime('test1.jpg')
>>> f
1223995325.0

since the beginning of (epoch)

Solution 2 - Python

os.stat()

import os
filename = "/etc/fstab"
statbuf = os.stat(filename)
print("Modification time: {}".format(statbuf.st_mtime))

Linux does not record the creation time of a file (for most fileystems).

Solution 3 - Python

New for python 3.4+ (see: pathlib)

import pathlib

path = Path('some/path/to/file.ext')
last_modified = path.stat().st_mtime

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBill the LizardView Question on Stackoverflow
Solution 1 - PythonJackView Answer on Stackoverflow
Solution 2 - PythonDouglas LeederView Answer on Stackoverflow
Solution 3 - PythonBrian BruggemanView Answer on Stackoverflow