-2

I am making an alarm clock program that will have to sleep (Not make noise) until 6:00AM. The problem I am having is that I cannot get the program to wait X seconds

Pseudo Code: X = 6:00AM - CurrentTime time.sleep(X)

Here is my code so far:

#Imports
import datetime
import time
import pygame

WORDS = ["Wake", "Me", "Tommorow"]

#Make J.A.R.V.I.S. Listen
mic.activeListen():

#Determine time and difference of time
x = datetime.datetime.now()
x = x.total_seconds
print(x)
x = datetime.timedelta()
x = float(x) #time.sleep() Requires a float value.
time.sleep(x) #Sleeps until 6:00 AM
pygame.mixer.init()
pygame.mixer.music.load("alarm.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
user3532319
  • 17
  • 1
  • 1
  • 1

2 Answers2

2

In order to create a datetime object representing 6:00am, you'd need to specify the date. E.g. if you want 6:00am today (assuming it happens in the future):

from datetime import datetime, date, time, timedelta
import time
d = date.today()
target_dt = datetime.combine(d, time(6,0))
td = target_dt - datetime.now()
time.sleep(td.total_seconds())

If you want 6am tomorrow, do:

d = date.today() + timedelta(days=1)
# the rest is the same...
shx2
  • 61,779
  • 13
  • 130
  • 153
  • I mis asked my question, I need to find the difference between CurrentTime and 6:00AM, any ideas there? – user3532319 Apr 14 '14 at 14:27
  • When I evaluate target_dt = datetime.combine(d, time(6,0)) In python command line it throws the error Python 3.4.0 >>> target_dt = datetime.combine(d, time(6,0)) Traceback (most recent call last): File "", line 1, in NameError: name 'datetime' is not defined >>> – user3532319 Apr 14 '14 at 19:26
  • @user3532319 did you run the import line? `from datetime import datetime, date, time, timedelta` – shx2 Apr 14 '14 at 20:34
0

You should not trust time.sleep() to stop waiting at the expected time, as any caught signal will terminate it (see answers to Upper limit in Python time.sleep()?).

Community
  • 1
  • 1
tpatja
  • 690
  • 4
  • 11