Edad de los archivos de impresión en segundos usando Python
Necesito mi script para descargar un nuevo archivo, si el anterior es lo suficientemente viejo. Establecí la edad máxima del archivo en segundos. Para que pueda volver a la pista con mi escritura de script necesito código de ejemplo, donde la edad del archivo se imprime en segundos.
3 answers
Esto muestra cómo encontrar la última hora de modificación de un archivo (o directorio):
Aquí está el número de segundos desde la Época, usando os.stat
import os
st=os.stat('/tmp')
mtime=st.st_mtime
print(mtime)
# 1325704746.52
O, de forma equivalente, usando os.camino.getmtime:
print(os.path.getmtime('/tmp'))
# 1325704746.52
Si quieres un datetime.datetime objeto:
import datetime
print("mdatetime = {}".format(datetime.datetime.fromtimestamp(mtime)))
# mdatetime = 2012-01-04 14:19:06.523398
O una cadena formateada usando time.ctime
import stat
print("last accessed => {}".format(time.ctime(st[stat.ST_ATIME])))
# last accessed => Wed Jan 4 14:09:55 2012
print("last modified => {}".format(time.ctime(st[stat.ST_MTIME])))
# last modified => Wed Jan 4 14:19:06 2012
print("last changed => {}".format(time.ctime(st[stat.ST_CTIME])))
# last changed => Wed Jan 4 14:19:06 2012
Aunque no lo mostré, hay equivalentes para encontrar el tiempo de acceso y el tiempo de cambio para todos estos método. Solo tienes que seguir los enlaces y buscar " atime "o"ctime".
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
2012-01-04 19:46:23
Otro enfoque (sé que no fui la primera respuesta, pero aquí va de todos modos):
import time, os, stat
def file_age_in_seconds(pathname):
return time.time() - os.stat(pathname)[stat.ST_MTIME]
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
2011-07-29 22:09:48
Use stat.M_TIME para obtener la última hora modificada y restarla de la hora actual.
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
2011-07-29 21:48:28