¿Cómo obtengo la última vez que se modificó un archivo en Python?


Asumiendo que el archivo existe (usando os.path.exists(filename) para primero asegurarme de que existe), ¿cómo muestro la última vez que se modificó un archivo? Esto es en Linux si eso hace alguna diferencia.

Author: Bill the Lizard, 2008-12-17

3 answers

Os.stat()

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

Linux no registra el tiempo de creación de un archivo (para la mayoría de los sistemas de archivos).

 46
Author: Douglas Leeder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-02 05:50:45
>>> import os
>>> f = os.path.getmtime('test1.jpg')
>>> f
1223995325.0

Desde el principio de (época)

 101
Author: Jack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-17 16:41:59

Nuevo para python 3.4+ (ver: pathlib )

import pathlib

path = Path('some/path/to/file.ext')
last_modified = path.stat().st_mtime
 4
Author: Brian Bruggeman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-24 16:17:13