[Python] How to create a Python 'alarm' which will act either today or tomorrow

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have been given a python script which allows me to mute the volume of my mac at a time I set so that any podcasts I'm listening to as I fall asleep won't wake me up once I am asleep.

    However, it will only act once the time given happens on that day, therefore if I try to activate it before midnight, it will mute the laptop immediately, which is not ideal because if I want to use it I have to wait for midnight to pass before I go to sleep.

    #!/usr/bin/env python3

    import datetime as dt
    import osascript
    import sys
    from threading import Timer

    def do_the_biz():
    osascript.osascript("set volume output volume 0")
    print("Night night")
    today = dt.datetime.now()
    dateString = today.strftime('%d-%m-%Y') + " " + sys.argv[1]
    newDate = today.strptime(dateString,'%d-%m-%Y %H:%M')
    delay = (newDate - dt.datetime.now()).total_seconds()
    Timer(delay,do_the_biz,()).start()


    So, a typical execution of this script looks like this:

    $./sleep.py 04:00


    and the command line will return the following once it has reached 4am, and then close the program:

    Night Night


    What I would like is to be able to manipulate the date so that the script will operate at the next available time of, for example, 4am - so it would essentially operate almost in the exact same way an alarm would. For this I could run an entirely different script of sleep.tomorrow.

    However, in an ideal world, I would like to be able to:

    • have the option to have another argument where I specify today or tomorrow and the program acts accordingly;
    • be able to cancel the process without having to close the terminal.

    I am new to python and have been having a hard time understanding the differences between the various datetime functions and the documention hasn't helped, so a brief explanation and comparison between what they input and output and how they interact would be gratefully appreciated.

    Continue reading...

Compartilhe esta Página