I've a log file which records log as:
- Format: DATE TIME VALUE
- Ex: 2016-07-28 16:54:32,504 -47.7669027319
I want to keep logs only for past 24 hours. Logging continues 24*7 at 2 samples/seconds, i.e. 172800 samples/24 hours. From https://stackoverflow.com/a/28057753/5954600 I found Python code, which works and I modified as per my requirement as:
import datetime
# for testing I'm using "seconds=60", which will be modified to "hours=24"
before_24h = str(datetime.datetime.now() - datetime.timedelta(seconds=60))
file = open("meter.log","r+")
logs = file.readlines()
file.seek(0)
for each_log in logs:
if each_log > before_24h:
file.write(each_log)
file.truncate()
file.close()
This code deletes all logs before 24 hours but writing 172800 lines to file will take some time. So I'm looking for efficient way to do it, if any.
Thanks in advance.