Search code examples
pythoncountdown

Read time(s) from .txt file, then countdown to that time


I have a text file called sorted_passes.txt with the following:

  • NOAA18 23/08/2020 10:56:46 Max Elev: 67
  • NOAA19 23/08/2020 19:08:02 Max Elev: 74
  • NOAA15 23/08/2020 20:12:44 Max Elev: 87
  • NOAA18 23/08/2020 22:19:47 Max Elev: 90

I would like to have a timer either do one of the following:

  1. Count down to the next time in the .txt file and then after that time, move to the next time, again, counting down.
  2. Count down to each time in the .txt file

My plan is to eventually have the countdown timer(s) display via a MAX7219 led board connected to raspberry pi.

So far, I have this python code:

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

Solution

  • This should get you started:

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

    This will print a countdown statement with how long it takes, sleeps a second. Or it will go to the next event until all lines are checked.

    You need to make sure the file dates are incremental (e.g. a new line is always later than the earlier lines).

    Example output (I manually changed the date in the last line):

    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