Python Forum

Full Version: How to acquire an imported file creation time
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone,

I have a number of pickle files and I wonder how can I get the creation date and time in python for every imported file.

Thanks in advance
The following will return dates on files.
Need to pass full pathlib filename (or just filename if in same directory as script)

import time
import datetime
from pathlib import Path
import os


def get_file_dates(filename):
    last_mod_time = datetime.datetime.fromtimestamp(filename.stat().st_mtime)
    create_date = datetime.datetime.fromtimestamp(filename.stat().st_ctime)
    return last_mod_time, create_date


if __name__ == '__main__':
    # Set current directory = script directory (not necessary if full path used).
    os.chdir(os.path.abspath(os.path.dirname(__file__)))

    filename = Path("newin.xlsx")
    moddate, createdate = get_file_dates(filename)

    print(f"File {filename} was created on {createdate}, and modified on {moddate}")
example:
python CheckFileDates.py
Output:
File newin.xlsx was created on 2021-09-07 10:44:36.218143, and modified on 2021-09-07 10:44:36.218143
Thank you for your reply

I get this error: 'str' object has no attribute 'state'
I see no "state" in the code. Do you mean "stat"? Please show the complete error stack trace (in [error] tags).
Also make sure you aree using pathlib (posix) paths