I've run a script that deletes all files in a folder after 5 minutes from the time they were last created or modified.
Taking into account the eventuality that some file is created at the moment of the change of the time zone, I implemented some conditions that make sure that the file is also deleted in the arc of those 5 minutes. The method I used is effective, but I learned from a more experienced programmer that there is a more efficient way, probably using some library or some method datetime
that I don't know.
I am a lover of clean code and I would like to know this other method to continue improving professionally. First of all, Thanks.
Here is the part of the code that concerns the matter:
# fTime es la fecha de ultima modificacion del archivo
# fPath es el directorio y nombre completo del archivo
now = datetime.now() # Obtiene hora actual
if now > fTime:
diff = now - fTime # Actua normalmente o cuando el tiempo va arriba de 1 o 2 horas en la zona horaria
else:
diff = fTime - now # Actua cuando el tiempo va atras de 1 o 2 horas en la zona horaria
minutes = diff.seconds / 60 # Transforma horas en minutos
if 55 < minutes < 65: # Arregla el tiempo si cambia de 1 o mas horas adelante o atras
fixTime = 60 - minutes
if -5 > fixTime > 5: # Elimina archivo con diferencia de 5 minutos adelante o atras respecto a la hora actual
remove(fPath)
else: # Si no hay cambios en la zona horaria el control pasa por aqui
if minutes > 5: # Elimina los archivos con 5 minutos de diferencia adelante respecto a la hora actual
remove(fPath)
Although it is impossible for us to know the way your experienced colleague was referring, I will share with you what I would do. In this way, according to what I understand of how the world works, the time zone change problems are indifferent.
What I would do is rely on Unix time , or POSIX, which is time zone agnostic in the sense that it measures the seconds since the first second of January 1, 1970 (UTC).
Thus, taking advantage of the fact that Python allows us to obtain the information, or metadata, of a file through the
lstat
module functionos
, and that within this information is included the moment in which the given file was created in Unix time, we can then simplify the algorithm you have created.In addition to this, we can get the current Unix time through the
time()
module methodtime
.Considering all of the above, we can write the following:
Update: I just noticed you say "created or modified". In that case, you can access the value you want via
file_metadata.st_mtime
.