从.txt文件中读取时间,然后倒计时



我有一个名为sorted_passes.txt的文本文件,其中包含以下内容:

  • NOAA18 2020年8月23日10:56:46最大海拔:67
  • NOAA 2020年8月23日19:08:02最高海拔:74
  • NOAA 15 2020年8月23日20:12:44最高海拔:87
  • NOAA 18 2020年8月23日22:19:47最高海拔:90

我想要一个计时器,可以执行以下操作之一:

  1. 在.txt文件中倒计时到下一次,然后在该时间之后,再次移动到下一个时间,倒计时
  2. 在.txt文件中倒计时到每次

我的计划是最终通过连接到树莓派的MAX7219 led板显示倒计时计时器。

到目前为止,我有这样的python代码:

# calculate time until next pass
from datetime import datetime
futuredate = datetime.strptime('10:56:46', '%H:%M:%S')
nowdate = datetime.now()
count = int((futuredate-nowdate).total_seconds())
days = count//86400
hours = (count-days*86400)//3600
minutes = (count-days*86400-hours*3600)//60
seconds = count-days*86400-hours*3600-minutes*60
print("Next Pass: {}h:{}m:{}s".format(hours, minutes, seconds))

这应该会让你开始:

from datetime import datetime
from time import sleep
def compare(event):
"""Return True if it's counting down, false if the time already passed"""
now = datetime.now()
if now <= event:
diff = event - now
print("Countdown: {}".format(diff))
return True
else:
return False

def extract_timestamp(line):
"""Extract datetime from string:
NOAA18 23/08/2020 10:56:46 Max Elev: 67
"""
time_stamp = line[7:][:-14]
time_event = datetime.strptime(time_stamp, '%d/%m/%Y %H:%M:%S')
return time_event
def open_file():
with open('sorted_passes.txt', 'r') as f:
return f.readlines()

data = open_file()
# iterate through the lines of the file
for line in data:
ts = extract_timestamp(line)
while compare(ts):
sleep(1)
else:
print("Next event")
continue
print("Finished")

这将打印一份倒计时声明,说明需要多长时间,睡一秒钟。或者它将转到下一个事件,直到所有行都被选中为止。

您需要确保文件日期是递增的(例如,新行总是晚于前几行(。

示例输出(我手动更改了最后一行中的日期(:

Next event
Next event
Next event
Countdown: 0:00:03.531014
Countdown: 0:00:02.526724
Countdown: 0:00:01.524277
Countdown: 0:00:00.518995
Finished

相关内容

最新更新