Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code for alarm clock

Tags:

python

I am writing a python code for implementing an alarm clock where I am putting some YouTube links in text file and the program will read the file. I have to set time whatever I want in any format and at that particular time program will pick a random link from those which are saved in the file and start playing. But in the if else part my program is falling in a infinite loop.

Can anyone please review my code where I am doing mistakes.

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"
like image 984
Sharmili Nag Avatar asked Sep 14 '26 15:09

Sharmili Nag


1 Answers

You are trying to compare apples with oranges in you time comparison:

>>> 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'>

If you compare the two different types, time.struct_time with datetime.datetime, you will see it is false even if the times recorded in these objects is the same.

>>> a == b
False

If you convert the struct_time to a datetime, the comparison will then work:

>>> 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'>

May I suggest that rather than loop and constantly compare the current time with your alarm clock time, you rather use the time.sleep() function. Subtract the current time from your alarm time and sleep for that number of seconds.

like image 192
leancz Avatar answered Sep 17 '26 04:09

leancz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!