闹钟的Python代码

时间:2016-11-11 09:02:29

标签: python

我正在编写一个用于实现闹钟的python代码,我将一些YouTube链接放在文本文件中,程序将读取该文件。我必须以任何格式设置我想要的时间,并且在特定时间程序将从文件中保存并开始播放的那些随机链接。 但是在if else部分,我的程序正处于无限循环中。

任何人都可以在我犯错的地方查看我的代码。

import random
import time
import webbrowser

from datetime import datetime
import subprocess

lines = open("C:\Python_code\Links.txt").read().splitlines()
mylines = random.choice(lines)
print(mylines)

time_input = str(raw_input("Please enter the time in HH:MM:SS format: "))
current_date = str(raw_input("Please enter the date in YYYY/MM/DD format: "))
selected_time = datetime.strptime('%s %s'%(current_date, time_input),"%Y/%m/%d  %H:%M:%S")
print "Time selected: ",selected_time

while True:
  if selected_time == time.localtime():
      print "Alarm Now"
      webbrowser.open(mylines)
      break
  else:
      print "no alarm"

3 个答案:

答案 0 :(得分:3)

您正试图在时间比较中比较苹果和橙子:

>>> import time
>>> a=time.localtime()
>>> a
time.struct_time(tm_year=2016, tm_mon=11, tm_mday=11, tm_hour=12, tm_min=20, tm_sec=13, tm_wday=4, tm_yday=316, tm_isdst=0)
>>> type(a)
<type 'time.struct_time'>

>>> from datetime import datetime
>>> b=datetime.strptime('2016/11/11 12:20:13',"%Y/%m/%d  %H:%M:%S")
>>> b
datetime.datetime(2016, 11, 11, 12, 20, 13)
>>> type(b)
<type 'datetime.datetime'>

如果比较两种不同类型time.struct_time和datetime.datetime,即使这些对象中记录的时间相同,您也会看到它是假的。

>>> a == b
False

如果将struct_time转换为日期时间,则比较将起作用:

>>> datetime.fromtimestamp(time.mktime(a))
datetime.datetime(2016, 11, 11, 12, 20, 13)
>>> c=datetime.fromtimestamp(time.mktime(a))
>>> b==c
True
>>> type(c)
<type 'datetime.datetime'>

我建议您不要循环并不断地将当前时间与闹钟时间进行比较,而是使用time.sleep()函数。从您的闹钟时间中减去当前时间并在该秒数内休眠。

答案 1 :(得分:0)

我们要报警

import time
import winsound
print("made by python.hub")
def myAlarm():
    try:
          myTime=list(map(int,input('enter the time in the m/sec').split()))
          if len(myTime)==3:
              total_sounds= myTime[0]*60*60+myTime[1]*60+myTime[2]
              time.sleep(total_sounds)
              frequency=2500
              duration=1000
              winsound.Beep(frequency , duration )
          else:
             print('please write the correct format as mentioned\n')
             myAlarm()
    except Exception as e:
        print('this is the exception',e,'please enter correct details')
        myAlarm()
    myAlarm()

答案 2 :(得分:-1)

您可能想尝试一下:

import datetime
print (datetime.datetime.today().strftime("%H"))
print(datetime.datetime.today().strftime("%M"))
hour=int(input("Enter a Hour: "))
minute=int(input("Enter a Minute: "))
while True:
    if hour == int(datetime.datetime.today().strftime("%H")) and minute == int(datetime.datetime.today().strftime("%M")):
        print("Alarm Raised")
        break
    else:
        print("Alarm Not Raised")
        break