Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีได้วันที่สร้างและแก้ไขไฟล์ใน Python

ดึงเวลาสร้างไฟล์: Windows ใช้ os.path.getctime(file_path) UNIX ไม่สามารถใช้ฟังก์ชันเดียวกันได้ เพราะคืนเวลาที่ attribute หรือ content เปลี่ยนล่าสุด UNIX ใช้ st_birthtime attribute ของ stat tuple

ตัวอย่าง

Windows:

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

คืนวินาทีนับจาก epoch สำหรับ UNIX:

import os
stat = os.stat(path_to_file)
try:
    print(stat.st_birthtime)
except AttributeError:
    # Linux ไม่มี st_birthtime ใช้ mtime แทน
    print(stat.st_mtime)

ผลลัพธ์

1505928271.0689342

ดึงเวลาแก้ไขไฟล์ ใช้ os.path.getmtime(path) รองรับ cross-platform

ตัวอย่าง

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