개발/파이썬

파일 생성 및 수정 날짜/시간을 얻는 방법

맨날치킨 2022. 12. 3. 19:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How do I get file creation and modification date/times?

파일 생성 및 수정 날짜/시간을 얻는 방법

 문제 내용 

What's the best cross-platform way to get file creation and modification dates/times, that works on both Linux and Windows?

Linux와 Windows 모두에서 작동하는 파일 생성 및 수정 날짜/시간을 얻을 수 있는 가장 좋은 교차 플랫폼 방법은 무엇입니까?

 

 

 

 높은 점수를 받은 Solution 

Getting some sort of modification date in a cross-platform way is easy - just call os.path.getmtime(path) and you'll get the Unix timestamp of when the file at path was last modified.

크로스 플랫폼 방식으로 일종의 수정 날짜를 얻는 것은 쉽습니다. os.path.getmtime(path)만 있으면 경로에 있는 파일이 마지막으로 수정된 시점의 유닉스 타임스탬프를 얻을 수 있습니다.

 

Getting file creation dates, on the other hand, is fiddly and platform-dependent, differing even between the three big OSes:

반면에 파일 생성 날짜를 얻는 것은 불안정하고 플랫폼에 따라 다르며, 심지어 다음과 같은 세 가지 주요 OS도 다릅니다.

 

Windows(윈도우)에서는 파일의 ctime(https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx)에 표시됨)이 생성 날짜를 저장합니다. Python에서 os.path.getctime() 또는 os.stat() 호출 결과의 .st_ctime 속성을 통해 이에 액세스할 수 있습니다. 이것은 유닉스에서 작동하지 않으며, 여기서 ctime은 파일의 속성이나 내용이 마지막으로 변경된 시간입니다.

Mac 및 일부 다른 Unix 기반 OS에서는 os.stat() 호출 결과의 .st_birthtime 속성을 사용할 수 있습니다.

리눅스에서 이것은 적어도 파이썬용 C 확장자를 작성하지 않고서는 현재 불가능하다. 리눅스에서 일반적으로 사용되는 일부 파일 시스템은 생성 날짜를 저장하지만(예: ext4는 st_crtime에 저장함) 리눅스 커널은 이들에 접근할 수 있는 방법을 제공하지 않는다. 또한 식별자 st_crtime이 현재 파이썬 소스의 어느 곳에도 기능하지 않는다는 것을 알 수 있다. 적어도 당신이 ext4에 있다면, 데이터는 파일 시스템의 inode에 첨부되지만, 그것에 접근하는 편리한 방법은 없다.

리눅스에서 차선책은 os.path.getmtime() 또는 os.stat() 결과의 .st_mtime 속성을 통해 파일의 mtime에 액세스하는 것이다. 이렇게 하면 파일 내용이 마지막으로 수정된 시간이 제공되며, 일부 사용 사례에 적합할 수 있습니다.

 

Putting this all together, cross-platform code should look something like this...

이 모든 것을 종합해보면, 크로스 플랫폼 코드는 다음과 같이 보일 것이다.
import os
import platform

def creation_date(path_to_file):
    """
    Try to get the date that a file was created, falling back to when it was
    last modified if that isn't possible.
    See http://stackoverflow.com/a/39501288/1709587 for explanation.
    """
    if platform.system() == 'Windows':
        return os.path.getctime(path_to_file)
    else:
        stat = os.stat(path_to_file)
        try:
            return stat.st_birthtime
        except AttributeError:
            # We're probably on Linux. No easy way to get creation dates here,
            # so we'll settle for when its content was last modified.
            return stat.st_mtime

 

 

 가장 최근 달린 Solution 

import os, time, datetime

file = "somefile.txt"
print(file)

print("Modified")
print(os.stat(file)[-2])
print(os.stat(file).st_mtime)
print(os.path.getmtime(file))

print()

print("Created")
print(os.stat(file)[-1])
print(os.stat(file).st_ctime)
print(os.path.getctime(file))

print()

modified = os.path.getmtime(file)
print("Date modified: "+time.ctime(modified))
print("Date modified:",datetime.datetime.fromtimestamp(modified))
year,month,day,hour,minute,second=time.localtime(modified)[:-3]
print("Date modified: %02d/%02d/%d %02d:%02d:%02d"%(day,month,year,hour,minute,second))

print()

created = os.path.getctime(file)
print("Date created: "+time.ctime(created))
print("Date created:",datetime.datetime.fromtimestamp(created))
year,month,day,hour,minute,second=time.localtime(created)[:-3]
print("Date created: %02d/%02d/%d %02d:%02d:%02d"%(day,month,year,hour,minute,second))

prints

결과물
somefile.txt
Modified
1429613446
1429613446.0
1429613446.0

Created
1517491049
1517491049.28306
1517491049.28306

Date modified: Tue Apr 21 11:50:46 2015
Date modified: 2015-04-21 11:50:46
Date modified: 21/04/2015 11:50:46

Date created: Thu Feb  1 13:17:29 2018
Date created: 2018-02-01 13:17:29.283060
Date created: 01/02/2018 13:17:29

 

Note: A file's ctime on Linux is slightly different than on Windows.
Windows users know theirs as "creation time".
Linux users know theirs as "change time".

참고: Linux에서 파일의 ctime은 Windows와 약간 다릅니다. Windows 사용자는 자신의 것을 "생성 시간"으로 알고 있습니다. 리눅스 사용자들은 그들의 것을 "변경 시간"으로 알고 있다.

 

 

 

출처 : https://stackoverflow.com/questions/237079/how-do-i-get-file-creation-and-modification-date-times

반응형