66

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.

Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861

3 Answers3

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

since the beginning of (epoch)

Jack
  • 19,841
  • 11
  • 47
  • 47
  • 1
    Thanks, this was helpful. This seems to be the more direct approach to my specific question, but the os.stat solution gives more information. – Bill the Lizard Dec 17 '08 at 17:08
  • 6
    I didn't know that there was an explicit function for this. Live and learn I guess. – Douglas Leeder Sep 04 '09 at 15:24
  • 2
    Probably the more portable solution – djhaskin987 Sep 05 '14 at 20:32
  • thank you for this solution – WhyWhat May 11 '20 at 11:31
  • This is the best answer for the specific question asked. The more generic stats give more information and is preferable when that additional information is needed, but when it's not - like in the scenario asked about here - this extraneous information and the extra layers are just unneeded burden. – Tom Feb 15 '21 at 22:34
68

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).

Douglas Leeder
  • 50,599
  • 9
  • 90
  • 136
42

New for python 3.4+ (see: pathlib)

import pathlib

path = Path('some/path/to/file.ext')
last_modified = path.stat().st_mtime
Brian Bruggeman
  • 4,536
  • 2
  • 32
  • 49
  • It seems like `pathlib` is useful for getting a file when you have an absolute path and aren't sure about the OS. But if you can assume that the file in question is in the same directory as your script, then it seems like the other approaches may be easier. – Teepeemm May 08 '18 at 21:33
  • 5
    pathlib handles relative paths. – Brian Bruggeman May 08 '18 at 23:32
  • In that case, I don't see a difference between `pathlib.Path("file.ext").stat()` and `os.stat("file.ext")`. – Teepeemm May 09 '18 at 00:47
  • 7
    pathlib is intended to provide an object oriented method for obtaining many of the features found in os and stat. It's not intended to replace but to live along side. Additionally, it becomes more handy when you need to pass around paths and you want access to file information or to open the file directly. – Brian Bruggeman May 09 '18 at 00:58
  • 1
    Right answer in 2021! – Massimo Rebuglio Nov 29 '21 at 03:53