Bibek Ghimire
Bibek Ghimire

Reputation: 562

how to detect change in hour of system time

I am trying to make a program in Python that beeps every hour. and no of beeps should be equal to no of hours. such as for 12 o'clock it should beep 12 times.

but I have no idea how to detect change in hour.

def bep(h):
    for i in range(h):
        winsound.Beep(2000,800)
        sleep(2)

the above code beeps for h no of times and

def hour():
    return hour=int(time.ctime(time.time()).split()[3].split(':')[0])

it gives the hour. but how to detect that hour has changed.

whether should I check every regular time interval and use previous hour and current hour to detect changes? I think this idea is not effective. because of time delay of interval time i.e. check current time every 5 second and compare two successive check to detect change in hours. is there any method to accomplish it directly.

Upvotes: 0

Views: 2646

Answers (1)

Rolf of Saxony
Rolf of Saxony

Reputation: 22438

At its simplest:

import datetime
import time
current = 0
while True:
    time.sleep(5)
    if datetime.datetime.now().hour != current:
        current = datetime.datetime.now().hour
        print "beep" , str(current)

Note you can test the code by using .minute rather than .hour Which will allow you to see if it fits your purposes.
You will have to replace the print "beep", str(current) with a call to your function bep(current)

Also you might want to consider adding a little extra code to your bep(h) function.

if h>12: h=h-12
if h == 0: h = 12

To ensure that for example: at 16:00 you only hear 4 beeps rather than 16 and at midnight, you hear 12 beeps, rather than none.

Upvotes: 1

Related Questions