Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print file age in seconds using Python

Tags:

python

file

I need my script to download new file, if the old one is old enough. I set the maximum age of file in seconds. So that I would get back on track with my script writing I need example code, where file age is printed out in seconds.

like image 815
Marko Avatar asked Jul 29 '11 21:07

Marko


People also ask

How do I get the size of a file in Python?

The python os module has stat() function where we can pass the file name as argument. This function returns a tuple structure that contains the file information. We can then get its st_size property to get the file size in bytes. Here is a simple program to print the file size in bytes and megabytes.

How do I know if a Python file is modified?

Python's os. path. getmtime() method can be used to determine when the given path was last modified.

How do I get a list of files in a directory in Python?

To get a list of all the files and folders in a particular directory in the filesystem, use os. listdir() in legacy versions of Python or os. scandir() in Python 3. x.


1 Answers

This shows how to find a file's (or directory's) last modification time:

Here are the number of seconds since the Epoch, using os.stat

import os st=os.stat('/tmp')     mtime=st.st_mtime print(mtime) # 1325704746.52 

Or, equivalently, using os.path.getmtime:

print(os.path.getmtime('/tmp')) # 1325704746.52 

If you want a datetime.datetime object:

import datetime          print("mdatetime = {}".format(datetime.datetime.fromtimestamp(mtime))) # mdatetime = 2012-01-04 14:19:06.523398 

Or a formated string using time.ctime

import stat print("last accessed => {}".format(time.ctime(st[stat.ST_ATIME]))) # last accessed => Wed Jan  4 14:09:55 2012 print("last modified => {}".format(time.ctime(st[stat.ST_MTIME]))) # last modified => Wed Jan  4 14:19:06 2012 print("last changed => {}".format(time.ctime(st[stat.ST_CTIME]))) # last changed => Wed Jan  4 14:19:06 2012 

Although I didn't show it, there are equivalents for finding the access time and change time for all these methods. Just follow the links and search for "atime" or "ctime".

like image 89
unutbu Avatar answered Sep 30 '22 05:09

unutbu