我正在尝试制作一个小脚本来使用文本文件中的时间,然后向该数字添加30分钟,然后与“当前时间”进行比较,以查看是否超过30分钟...
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)
任何帮助将不胜感激,我不知道如何正确地做到这一点。
代替在当前时间创建字符串,而是使用以下示例分析从文件读取的字符串datetime.datetime.strftime()
:
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():
这将检查是否已超过30分钟。
您可能应该在写入文件的信息中包括日期。如果您不这样做,那么23:30:45
永远不会是今天的“ 30分钟前” 。
如果您不需要时间戳来使人可读,那么只需写下自UNIX时代以来的秒数即可:
timecheck.write(str(time.time()))
这是一个浮点值,您可以使用以下方法再次读取它:
last_timecheck = float(timecheck.read())
由于它是数字表示形式,因此您可以通过以下方法测试是否经过了30分钟:
if last_timecheck + 30 <= time.time():
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句