我正在尝试为闹钟编写python代码。
我有两个疑问-
1)除非我在每个数字前添加0,否则不会发生本地时间与用户输入时间之间的比较。例如-h:m:s = 08:09:35。如果我键入-8:9:35
,它将不起作用
2)当按下任意键时如何停止闹钟? “输入”命令不起作用。
代码:
#strfime is of type string
#localtime is of time int
#using strftime
import time
from pygame import mixer
def sound():
mixer.init()
mixer.music.load("F:\learn\python\music1.mp3") #file is 28 seconds long
def userinput():
print("current time is: ",time.strftime("%H:%M:%S"))
h=(input("Enter the hour: "))
m=(input("Enter the minutes: "))
s=(input("Enter the seconds: "))
alarm(h,m,s)
def alarm(h,m,s):
n=2 #rings twice in 1 minute.
while True:
if time.strftime("%H") == h and time.strftime("%M") == m and time.strftime("%S") == s:
print("wake up!!!! \n")
break
sound()
while n>0: #code for ringing twice in a minute.
mixer.music.play()
time.sleep(30) #alarm should stop when any key pressed.
mixer.music.stop()
n-=1
snooze_in = input("Do you want to snooze? press y or n. ")
if snooze_in == 'y':
print("The alarm will start in 5 seconds")
time.sleep(5) #snooze for x seconds
h=time.strftime("%H")
m=time.strftime("%M")
s=time.strftime("%S")
return alarm(h,m,s)
else:
exit()
if __name__=="__main__":
userinput()
答案 0 :(得分:0)
您可以使用datetime对象,然后从结束日期时间中减去开始时间,以获得一个timedelta对象。然后,使用时间增量的total_seconds
来计算结束时间(以毫秒为单位)(通过将结束时间添加到pygame.time.get_ticks()
中),并在警报时间-pygame.time.get_ticks()小于0时播放警报声音。
要停止计时器,您可以将计时器代码放入if子句(if timer_active:
)中,并在用户按下键( S )时设置timer_active = False
)。
import datetime
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
SOUND = pg.mixer.Sound(r"C:\Dokumente\Pythonprogramme\win3.wav")
def main():
start = datetime.datetime.now()
print("current time is: ", start)
h = int(input("Enter the hour: "))
m = int(input("Enter the minutes: "))
s = int(input("Enter the seconds: "))
# I just pass the current year, month and day here, so it'll
# work only if the end time is on the same day.
end = datetime.datetime(start.year, start.month, start.day, h, m, s)
timedelta = end-start
alarm_time = pg.time.get_ticks() + timedelta.total_seconds()*1000
repeat_time = 3000 # Repeat the alarm after 3000 ms.
timer_active = True
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
elif event.type == pg.KEYDOWN:
if event.key == pg.K_s:
# Stop the sound and the timer.
SOUND.stop()
timer_active = False
if timer_active:
if alarm_time - pg.time.get_ticks() < 0: # Time is up.
SOUND.play() # Play the sound.
# Restart the timer by adding the repeat time to the current time.
alarm_time = pg.time.get_ticks() + repeat_time
screen.fill(BG_COLOR)
pg.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
pg.quit()
请注意,此示例仅在结束时间是同一天时有效。