python - 从 .txt 文件中读取时间,然后倒计时到该时间
问题描述
我有一个名为 sorted_passes.txt 的文本文件,其中包含以下内容:
- NOAA18 23/08/2020 10:56:46 最大海拔:67
- NOAA19 23/08/2020 19:08:02 最大海拔:74
- NOAA15 23/08/2020 20:12:44 最大海拔:87
- NOAA18 23/08/2020 22:19:47 最大海拔:90
我想要一个计时器,要么执行以下操作之一:
- 倒计时到 .txt 文件中的下一次,然后在该时间之后,移动到下一次,再次倒计时。
- .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
推荐阅读
- python - 安装 apache-airflow:alembic 失败
- reactjs - React Material-UI 文本字段填充顶部 - 泰语
- java - Spring Boot CORS 设置:CrossOrigin 注释有效,addCorsMappings 无效
- r - 将列表取消嵌套到 R 中的字符串的一般方法
- twilio - 是否可以将音频流式传输到实时 Twilio 电话?
- java - 带有列表的 Solr 查询?
- vue.js - 如何检测实际值的变化而不仅仅是 OnChange nuxt vuetify
- javascript - Firefox 问题:焦点更改时输入文本元素周围的红色边框
- c# - 我能否在 KeyDown 事件期间获取数据网格单元格的当前值
- python - 导入 pandas 模块,“pickle”模块的属性错误