Search code examples
python-3.7ctime

Python convert ctime to days since access


I have a file access time in the ctime format - but what I really need is the days since the file was last accessed. How do I convert my ctime date to days since last access?

So this:

fileStatObject = os.stat( iDir + "/" + fileName )
accessTime = time.ctime( fileStatObject[stat.ST_ATIME] )
print accessTime

Results in this: Tue Jun 23 16:06:04 2020

But what I need is this: 113


Solution

  • Just don't call ctime on it - that converts a timestamp to a string representation of the timestamp. Instead, you can find how much time has elapsed since that timestamp, and represent that in days:

    file_stat = os.stat(os.path.join(i_dir, file_name))
    access_timestamp = datetime.datetime.fromtimestamp(file_stat[stat.ST_ATIME])
    elapsed = datetime.datetime.now() - access_timestamp
    print(f"File was accessed {elapsed.days} days ago")
    

    You may wish to do further rounding of the elapsed time, but this should serve to illustrate how to more forward.

    You should also be aware of timezone issues. You might need to use utcnow() instead of now(); I haven't addressed this issue in this answer.