首页 > 解决方案 > 从 .txt 文件中读取时间,然后倒计时到该时间

问题描述

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

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

  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))

标签: pythoncountdown

解决方案


这应该让你开始:

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

推荐阅读