principlepythonMinor
Compare last modification time with specfied time
Viewed 0 times
lastwithspecfiedtimemodificationcompare
Problem
I'm writing a function in Python that compares the modification time of a file in Linux (using os.stat) with a specific time and compare the dates. If the modification date is older than the date I specified, an event should happen.
It is working but I have the feeling that this could be largely improved, because there are so many time conversions. Can you give me a hint on how I can make it better?
import os
import time
import datetime
# File Modification time in seconds since epoch
file_mod_time = round(os.stat(file).st_mtime)
# Time in seconds since epoch for time, in which logfile can be unmodified.
t = datetime.datetime.today() - datetime.timedelta(minutes=30)
should_time = round(time.mktime(t.timetuple()))
# Time in minutes since last modification of file
last_time = round((int(time.time()) - file_mod_time) / 60, 2)
if (file_mod_time - should_time) < args.time:
print "CRITICAL:", file, "last modified", last_time, "minutes. Threshold set to 30 minutes"
else:
print "OK. Command completed successfully", last_time, "minutes ago."It is working but I have the feeling that this could be largely improved, because there are so many time conversions. Can you give me a hint on how I can make it better?
Solution
For floating-point time values, go straight to
I used string formatting to handle the rounding for you; just work with the float values in the calculations.
time.time() and not use datetime:file_mod_time = os.stat(file).st_mtime
# Time in seconds since epoch for time, in which logfile can be unmodified.
should_time = time.time() - (30 * 60)
# Time in minutes since last modification of file
last_time = (time.time() - file_mod_time) / 60
if (file_mod_time - should_time) < args.time:
print "CRITICAL: {} last modified {:.2f} minutes. Threshold set to 30 minutes".format(last_time, file, last_time)
else:
print "OK. Command completed successfully {:.2f} minutes ago.".format(last_time)I used string formatting to handle the rounding for you; just work with the float values in the calculations.
Code Snippets
file_mod_time = os.stat(file).st_mtime
# Time in seconds since epoch for time, in which logfile can be unmodified.
should_time = time.time() - (30 * 60)
# Time in minutes since last modification of file
last_time = (time.time() - file_mod_time) / 60
if (file_mod_time - should_time) < args.time:
print "CRITICAL: {} last modified {:.2f} minutes. Threshold set to 30 minutes".format(last_time, file, last_time)
else:
print "OK. Command completed successfully {:.2f} minutes ago.".format(last_time)Context
StackExchange Code Review Q#37465, answer score: 5
Revisions (0)
No revisions yet.