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

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.

Leave a Reply