Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I say to Python to do an instruction at a given time?

I want that a specific time of the day (for example 10:00:00), one of my if condition activates.

For example:

if time is 10:00:00:
print("Hello world")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Imortant: I already read this: Python script to do something at the same time every day

But I don’t want to use a function!

>Solution :

You could easy use datetime to help you with that.

import datetime
from time import sleep

timing = [10, 0, 0] # Hour, minute, second, in 24 hour time

while True: # Repeat forever
    now = datetime.datetime.now()
    data = [now.hour, now.minute, now.second]
    if data == timing:
        # Code to be executed
        print("Hello World")
        #######
        sleep(1) # To ensure the command is not repeated again
        # break # Uncomment this if you want to execute the command only once

Make sure that I indented it properly, because one space can tick python off :).

The way that it works:
import datetime and from time import sleep import the necessary modules and functions that you will need.

Modules needed:
datetime
time.sleep

Now we’re set.
timing = [10,0,0] sets the time that you want to use (you’ll see why later)

while True repeats the loop… on and on and on.

now = datetime.datetime.now() creates a shortcut for such a long piece of text.

data == timing makes sure the time matches the timing you asked.

Note that the timing is in UTC
Go to Getting the correct timezone offset in Python using local timezone to know how to find your offset.

An offset of UTC-0200 (Or -7200 seconds) means that you need to ADD 2 hours to your time to get UTC. Or, if your time zone is UTC+0200, SUBSTRACT 2 hours from your time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading