报警的Python代码

2024-04-28 14:29:26 发布

您现在位置: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"

Tags: 文件import程序inputdatetimedateiftime
2条回答

你可能想试试这个:

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

在你的时间比较中,你试图将苹果与桔子进行比较:

>>> 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,即使这些对象中记录的时间相同,也会看到它为false。

>>> a == b
False

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

>>> 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()函数,而不是循环并不断比较当前时间和闹钟时间。从你的报警时间中减去当前时间,然后再睡眠几秒钟。

相关问题 更多 >