I'm trying to compare my files with the timestamp.
For example, there is a directory with files, like
a.xls, a.log, a.txt
b.xls, b.log, b.txt
c.xls, c.log, c.txt
here i have to find whether the timestamp(datetime) of a.log and a.txt is greater than timestamp of a.xls
I did research about how to get a timestamp of a file, comparing timestamp of two files.
I don't know whether I'm going in a correct direction.
Please direct me how to look into this problem and give some logical guidance.
Asked
Active
Viewed 767 times
1

JoJo
- 67
- 8
-
1https://stackoverflow.com/help/how-to-ask This question should help you: https://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python – L.Clarkson May 04 '20 at 18:02
-
@L.Clarkson thanks for the suggestion – JoJo May 05 '20 at 13:34
2 Answers
2
I have managed to write a code for the above question.
import os
path = 'D:/Newfolder/A'
xls_file = []
for i in os.listdir(path):
if i.endswith('xls'):
file_name = (i.split('.')[0])
ext_name = (i.split('.')[1])
xls_file.append(file_name)
for fname in os.listdir(path):
for i in xls_file:
if fname.__contains__(i) and not fname.endswith('xls'):
log_txt = os.path.getmtime(path+'/'+fname)
xls_tym = os.path.getmtime(path+'/'+i+'.xls')
if xls_tym < log_txt:
pass
else:
print(i+'.xls')
It may not be the clean code,but i think the code works fine
Please suggest if any changes had to be made

JoJo
- 67
- 8
-
1A suggestion, have a look at [pathlib](https://docs.python.org/3/library/pathlib.html) and [glob](https://docs.python.org/3/library/glob.html) for the handling of paths and filenames. Also, avoid the direct usage of dunderscore methods like `fname.__contains__(i)` - there're more readable alternatives like e.g. `i in fname`. – FObersteiner May 06 '20 at 07:33
1
In Python if you are able to create a datetime object then you can compare them using comparison operators.
So to get a datetime object of your file you can do this:
modTimesinceEpoc = os.path.getmtime(filePath)
# Convert seconds since epoch to readable timestamp
modificationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modTimesinceEpoc))
Then you can directly use the timestamp and compare them and get your desired output.
Hope this helps.

Anmol Batra
- 159
- 1
- 8