Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách lấy thời gian tạo và sửa file bằng Python?


Để lấy thời gian tạo file, dùng os.path.getctime(file_path) trên Windows. Trên UNIX, hàm này trả về lần cuối thuộc tính/nội dung file thay đổi. Để lấy thời gian tạo trên UNIX, dùng thuộc tính st_birthtime của tuple stat.

Ví dụ

Trên Windows:

>>> import os
>>> print(os.path.getctime('my_file'))
1505928271.0689342

Trả về giây từ epoch. Trên UNIX:

import os
stat = os.stat(path_to_file)
try:
    print(stat.st_birthtime)
except AttributeError:
    # Có thể Linux. Không dễ lấy creation date,
    # dùng thời gian sửa nội dung cuối.
    print(stat.st_mtime)

Kết quả

Sẽ cho ra:

1505928271.0689342

Để lấy thời gian sửa file, dùng os.path.getmtime(path), cross-platform. Ví dụ:

>>> import os
>>> print(os.path.getmtime('my_file'))
1505928275.3081832