pyhton에서 파일의 수정 날짜가 한시간 이내인지 확인

Python에서 특정 파일의 수정 날짜가 한 시간 이내인지 확인하기 위해서는 os.path 모듈과 datetime 모듈을 사용할 수 있습니다. 다음은 그 예시입니다.

import os
from datetime import datetime, timedelta

file_path = "path/to/file.txt"

if os.path.exists(file_path):
    file_modified_time = os.path.getmtime(file_path)
    current_time = datetime.now().timestamp()
    one_hour_ago = current_time - timedelta(hours=1).total_seconds()

    if file_modified_time >= one_hour_ago:
        print("File was modified within the last hour.")
    else:
        print("File was not modified within the last hour.")
else:
    print("File does not exist.")

위의 예시에서는 먼저 os.path.exists() 함수를 사용하여 파일의 존재 여부를 확인합니다. 그런 다음 os.path.getmtime() 함수를 사용하여 파일의 수정 시간을 가져옵니다. datetime.now().timestamp()를 사용하여 현재 시간을 구하고, timedelta(hours=1).total_seconds()를 사용하여 한 시간 전의 시간을 계산합니다.

그 후, 파일의 수정 시간 file_modified_time과 한 시간 전의 시간 one_hour_ago를 비교하여 파일이 한 시간 이내에 수정되었는지 여부를 확인합니다. 비교 결과에 따라 적절한 메시지를 출력합니다.

위의 예시는 파일이 존재하는 경우에만 작동합니다. 파일이 존재하지 않는 경우에는 해당하는 메시지를 출력합니다. os.path.exists() 함수를 사용하여 파일의 존재 여부를 미리 확인하는 것이 좋습니다.

Leave a Comment

Verified by MonsterInsights