Reputation: 5769
I'm trying to make a little script to use the time from a text file and then add 30 minutes to that number, then compare against "currenttime" to see if 30+ minutes have passed...
import os
from time import time, sleep, strftime
with open('timecheck.txt') as timecheck:
last_timecheck = timecheck.read().strip()
print last_timecheck
currenttime = strftime('%H:%M:%S')
if last_timecheck + 30 >= currenttime:
if os.path.exists("../test.csv"):
with open("timecheck.txt", 'wb') as timecheck:
timecheck.write("1")
else:
currenttime = strftime('%H:%M:%S')
with open("timecheck.txt", 'wb') as timecheck:
timecheck.write(currenttime)
Any help would be appreciated, I can't figure out how to do it correctly.
Upvotes: 1
Views: 338
Reputation: 1121256
Instead of creating a string for the current time, parse the string read from the file, using datetime.datetime.strftime()
for example:
import datetime
last_timecheck = datetime.datetime.strptime(last_timecheck, '%H:%M:%S')
last_timecheck = datetime.datetime.combine(datetime.date.today(), last_timecheck.time())
if last_timecheck + datetime.timedelta(minutes=30) <= datetime.datetime.now():
This checks if more than 30 minutes have passed.
You probably should include the date in the information you write to the file. If you don't, then 23:30:45
will never be '30 minutes ago' on the current day.
If you don't need the timestamp to be human-readable, just write seconds since the UNIX epoch:
timecheck.write(str(time.time()))
That's a floating point value, and you can read it again with:
last_timecheck = float(timecheck.read())
Since it is a numeric representation, you can then test if 30 minutes have passed with:
if last_timecheck + 30 <= time.time():
Upvotes: 5