lunes, mayo 03, 2021

Python Snippets: path, time, datetime

Este es un snippet sobre encontrar el archivo mas reciente de un directorio y calcular el tiempo que ha pasado desde su creación, esto es solo la base para una función que busco hacer para un script 


import glob
import os.path
import time
from datetime import datetime

folder_path = 'D:\\python\\doodles\\'
file_type = '*.txt'
now = datetime.now()

# get the most recent file from directory
files = glob.glob(folder_path +file_type)
latest_file = max(files, key=os.path.getctime)

# get the creation time from the most recent file
latest_creation_ctime = os.path.getctime(latest_file)
latest_creation_time = datetime.fromtimestamp(latest_creation_ctime)

# calculate the diference
duration = now - latest_creation_time
duration_in_seconds = duration.total_seconds() 

# print the number of minutes since the file was created
print(int(duration_in_seconds)/60)

No hay comentarios: