1
import time
import webbrowser

print(time.ctime())

targetTime = time.ctime()


if(targetTime == "Tue May 01 11:05:17 2018"):    
    webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")

This is what I tried already and it doesn't open the link when the time comes. I read through the time library but I couldn't find anything to help me. My target is for the program to open a link at a time that I want. Any help appreciated.

Bogdan
  • 47
  • 1
  • 1
  • 3
  • In general, programming is not magic. Unless you keep updating the time (and comparing it to a time instead of a string), this won't work. – Mad Physicist May 01 '18 at 18:11
  • I did just started a basic Python tutorial where he uses time.sleep in order to achieve the same thing but my problem is that I might not start the program at the same time as yesterday so that will mess me up. That is why i asked here, because I want to run the program and it will do my function at a time I want. – Bogdan May 01 '18 at 18:20

2 Answers2

11

Python comes built-in with a simple scheduling library called sched that supports this.

import sched, time

def action():
    webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")

# Set up scheduler
s = sched.scheduler(time.localtime, time.sleep)
# Schedule when you want the action to occur
s.enterabs(time.strptime('Tue May 01 11:05:17 2018'), 0, action)
# Block until the action has been run
s.run()
scnerd
  • 5,836
  • 2
  • 21
  • 36
  • datetime.datetime(2023, 8, 23, 20, 48, 40, 743486) `TypeError: '>' not supported between instances of 'datetime.datetime' and 'time.struct_time'` – CS QGB Aug 23 '23 at 12:50
  • \sched.py in run(self, blocking) if not blocking: return time - now delayfunc(time - now) – CS QGB Aug 23 '23 at 13:16
  • @CSQGB Docs for sched are here: https://docs.python.org/3/library/sched.html They make the point that the units (and hence object types) of time are up to you. I used time_struct objects in the above example, which isn't compatible with the datetime object you show. If you want to use datetime and timedelta objects, I'm sure you can make that work too, but you'll need to adjust the call to `sched.scheduler` or find a library that does the type conversions for you. – scnerd Aug 24 '23 at 15:17
6

If you don't mind using third party modules, there's Python pause:

import pause
from datetime import datetime

pause.until(datetime(2018, 5, 1, 11, 5, 17))
webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
fferri
  • 18,285
  • 5
  • 46
  • 95