티스토리 뷰

728x90

Python에서 어떤 파일의 생성 시간, 수정 시간을 확인하는 방법에 대해서 알아보겠습니다.

 

파일 생성 날짜/시간 확인

os.stat(file)은 인자로 전달된 파일에 대한 정보를 stat_result 객체로 리턴합니다.

 

stat_result는 st_ctime 변수로 파일 생성 날짜를 저장합니다.

 

아래와 같이 생성 날짜를 가져올 수 있습니다.

import os
import time

file_path = 'sample.txt'  # 생성 날짜를 확인하려는 파일 경로

if os.path.exists(file_path):
    file_stat = os.stat(file_path)
    created_timestamp = file_stat.st_ctime
    created_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(created_timestamp))
    print(f"파일 생성 날짜: {created_date}")  # 파일 생성 날짜: 2023-09-16 19:55:34
else:
    print("파일이 존재하지 않습니다.")

 

파일 수정 날짜/시간 확인

동일한 방법으로 os.stat()으로 파일 정보를 가져오고, st_mtime으로 파일이 수정된 시간 정보를 가져올 수 있습니다.

import os
import time

file_path = 'sample.txt'  # 수정 날짜를 확인하려는 파일 경로

if os.path.exists(file_path):
    file_stat = os.stat(file_path)
    modified_timestamp = file_stat.st_mtime
    modified_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modified_timestamp))
    print(f"파일 수정 날짜: {modified_date}")  # 파일 수정 날짜: 2023-09-16 19:55:34
else:
    print("파일이 존재하지 않습니다.")

 

st_mtime과 st_ctime 외에, 아래와 같은 정보들도 제공합니다.

  • st_uid : 파일의 uid
  • st_gid : 파일의 gid
  • st_size : 파일의 크기 (byte)
  • st_atime : 마지막 access 시간
  • st_ino : inode 번호
728x90