Program Tip

Python에서 파일 생성 및 수정 날짜 / 시간을 얻는 방법은 무엇입니까?

programtip 2020. 9. 28. 09:59
반응형

Python에서 파일 생성 및 수정 날짜 / 시간을 얻는 방법은 무엇입니까?


파일 생성 및 수정 날짜에 따라 몇 가지 작업을 수행해야하지만 Linux 및 Windows에서 실행해야하는 스크립트가 있습니다.

Python에서 파일 생성 및 수정 날짜 / 시간을 얻는 가장 좋은 크로스 플랫폼 방법 은 무엇입니까 ?


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

반면에 파일 생성 날짜를 얻는 것은 까다 롭고 플랫폼에 따라 다르며 세 가지 큰 OS 간에도 다릅니다.

이 모든 것을 종합하면 크로스 플랫폼 코드는 다음과 같이 보일 것입니다.

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

몇 가지 선택이 있습니다. 하나의 경우 os.path.getmtimeos.path.getctime기능을 사용할 수 있습니다 .

import os.path, time
print("last modified: %s" % time.ctime(os.path.getmtime(file)))
print("created: %s" % time.ctime(os.path.getctime(file)))

다른 옵션은 다음을 사용하는 것입니다 os.stat.

import os, time
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
print("last modified: %s" % time.ctime(mtime))

참고 : ctime()않습니다 하지 * 괜찬아 시스템에서 생성 시간을 참조 아니라 마지막 시간은 아이 노드의 데이터가 변경되었습니다. (재미있는 블로그 게시물에 대한 링크를 제공하여 댓글에서 그 사실을 더 명확하게 해준 kojiro에게 감사드립니다)


이를 위해 사용하는 가장 좋은 함수는 os.path.getmtime () 입니다. 내부적으로 이것은 os.stat(filename).st_mtime.

datetime 모듈은 타임 스탬프를 조작하는 데 가장 적합하므로 다음 datetime과 같은 객체 로 수정 날짜를 가져올 수 있습니다 .

import os
import datetime
def modification_date(filename):
    t = os.path.getmtime(filename)
    return datetime.datetime.fromtimestamp(t)

사용 예 :

>>> d = modification_date('/var/log/syslog')
>>> print d
2009-10-06 10:50:01
>>> print repr(d)
datetime.datetime(2009, 10, 6, 10, 50, 1)

os.stat https://docs.python.org/2/library/stat.html#module-stat

편집 : 최신 코드에서는 아마도 os.path.getmtime () (Christian Oudard에게 감사드립니다 )을 사용해야
하지만 (OS에서 지원하는 경우) 분수 초와 함께 time_t의 부동 소수점 값을 반환합니다.


모드 시간을 얻는 방법은 os.path.getmtime () 또는 os.stat () 두 가지가 있지만 ctime은 신뢰할 수있는 크로스 플랫폼이 아닙니다 (아래 참조).

os.path.getmtime ()

getmtime(path)
Return the time of last modification of path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number.

os.stat()

stat(path)
Perform a stat() system call on the given path. The return value is an object whose attributes correspond to the members of the stat structure, namely: st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid (user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes), st_atime (time of most recent access), st_mtime (time of most recent content modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
>>> 

In the above example you would use statinfo.st_mtime or statinfo.st_ctime to get the mtime and ctime, respectively.


os.stat returns a named tuple with st_mtime and st_ctime attributes. The modification time is st_mtime on both platforms; unfortunately, on Windows, ctime means "creation time", whereas on POSIX it means "change time". I'm not aware of any way to get the creation time on POSIX platforms.


In Python 3.4 and above, you can use the object oriented pathlib module interface which includes wrappers for much of the os module. Here is an example of getting the file stats.

>>> import pathlib
>>> fname = pathlib.Path('test.py')
>>> assert fname.exists(), f'No such file: {fname}'  # check that the file exists
>>> print(fname.stat())
os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272)

For more information about what os.stat_result contains, refer to the documentation. For the modification time you want fname.stat().st_mtime:

>>> import datetime
>>> mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime)
>>> print(mtime)
datetime.datetime(2018, 10, 17, 10, 49, 0, 249980)

If you want the creation time on Windows, or the most recent metadata change on Unix, you would use fname.stat().st_ctime:

>>> ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime)
>>> print(ctime)
datetime.datetime(2018, 4, 11, 16, 57, 52, 151953)

This article has more helpful info and examples for the pathlib module.


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

>>> import os
>>> os.stat('feedparser.py').st_mtime
1136961142.0
>>> os.stat('feedparser.py').st_ctime
1222664012.233
>>> 

If following symbolic links is not important, you can also use the os.lstat builtin.

>>> os.lstat("2048.py")
posix.stat_result(st_mode=33188, st_ino=4172202, st_dev=16777218L, st_nlink=1, st_uid=501, st_gid=20, st_size=2078, st_atime=1423378041, st_mtime=1423377552, st_ctime=1423377553)
>>> os.lstat("2048.py").st_atime
1423378041.0

os.stat does include the creation time. There's just no definition of st_anything for the element of os.stat() that contains the time.

So try this:

os.stat('feedparser.py')[8]

Compare that with your create date on the file in ls -lah

They should be the same.


It may worth taking a look at the crtime library which implements cross-platform access to the file creation time.

from crtime import get_crtimes_in_dir

for fname, date in get_crtimes_in_dir(".", raise_on_error=True, as_epoch=False):
    print(fname, date)
    # file_a.py Mon Mar 18 20:51:18 CET 2019

I was able to get creation time on posix by running the system's stat command and parsing the output.

commands.getoutput('stat FILENAME').split('\"')[7]

Running stat outside of python from Terminal (OS X) returned:

805306374 3382786932 -rwx------ 1 km staff 0 1098083 "Aug 29 12:02:05 2013" "Aug 29 12:02:05 2013" "Aug 29 12:02:20 2013" "Aug 27 12:35:28 2013" 61440 2150 0 testfile.txt

... where the fourth datetime is the file creation (rather than ctime change time as other comments noted).

참고URL : https://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python

반응형