I would like to have my program reference the current time in Python.
But my program keeps printing and referencing a timestamp. I am using Python3.5.3.
import time
timenow = time.strftime("%X")
awake = "06:00:00" # turn on the lights at 6am
sleep = "22:00:00" # turn off the lights at 10pm
while True:
print (timenow) # print the current time
if awake <= timenow:
print ("Lights On")
elif timenow >= sleep:
print ("Lights Off")
My current output is...
21:55:46
Lights On
21:55:46
Lights On
21:55:46
Lights On
This might work as well.
If you are referencing time as date part that can be represented an int. I guess its better to compare numbers in this case rather then strings (as in your example).
import datetime
on = 6
off = 22
while True:
ctime = datetime.datetime.now()
status = 'Lights On' if on < ctime.hour < off else 'Lights Off'
print('{}: {}'.format(ctime.strftime('%X'), status))
I think you just need to move 1 line into the while loop:
import time
awake = "06:00:00" # turn on the lights at 6am
sleep = "22:00:00" # turn off the lights at 10pm
while True:
timenow = time.strftime("%X") #moved this line into the while loop
print (timenow) # print the current time
if awake <= timenow:
print ("Lights On")
elif timenow >= sleep:
print ("Lights Off")
The output should now look like:
Lights On
08:50:22
Lights On
08:50:23
Lights On
08:50:24
In the question, timenow gets set and is never updated. So move that into the while loop flow so it gets created each time. Just as good programing practice you may also want to toss a pause in there so it's just not hammering the CPU in the loop. You could put this at the end of the while loop and it will wait 1 second before looping again:
....
elif timenow >= sleep:
print ("Lights Off")
time.sleep(1)
Related
I trying to create a timer for my quiz game. It should reset after every right question. But problem with my code is that it keeps increasing speed after every time it resets.
timeCount = 30
def countdown():
global timeCount
while timeCount > 0:
print(timeCount)
sleep(1)
timeCount -= 1
else:
print("Time Out!")
I think this is what you are trying to do:
import time
timeCount = 30
start = time.time()
seconds = 0
def countdown():
global timeCount
global seconds
while seconds < timeCount:
now = time.time()
seconds = now - start
print(timeCount - seconds)
else:
print("Time Out!")
countdown()
This teaches you how to use time.time. You can take away seconds from timeCount to make a timer that goes down from 30 to 0. When the seconds hits 30, you can end the loop and print "Time out". You can truncate the unnecessary floating point values, since i am assuming floating point numbers doesn't look good on a quiz timer and is unnecessary as well.
seconds = int(seconds)
You can use the function time.perf_counter() :
import time
start=time.perf_counter()
time.sleep(1) #you can replace the sleep function with the action you want to monitor
end=time.perf_counter()
print('elapsed time : ',end-start)
In the example above, time.perf_counter() evaluated the time when it is called so it gives you the elapsed time between the two call.
if you want to use your current logic :
Your 'global' statement means that your are going to modify the 'timeCount' variable during the execution of your code. To fix it, you can use a new local variable in your function (called 'local_count' in the below solution), like this you reset the countdown each time you call your function :
import time
timeCount = 30
def countdown():
local_count = timeCount
while local_count > 0:
print(local_count)
time.sleep(1)
local_count -= 1
print("Time Out!")
So I'm making a little speed game. A random letter is going to be generated by a function, right after that, I want the program to wait some seconds. If nothing is pressed, you will lose and your record will be displayed If you press the right key, another random letter is going to be displayed. I used the time function and simulated a cronometer that lasts in a range (0,2). This is what I have so far. It works, the thing is, it displays the first letter, if you press it wrong you lose (good) but even if you press it right, the cronometer obviously keeps running, so it gets to 2 and you lose. I want it to stop and reset after I hit the key, but I have no idea of how to do it. Im new in programming so I'm sorry if you don't get something.
import string
import random
import msvcrt
import time
def generarletra():
string.ascii_lowercase
letra = random.choice(string.ascii_lowercase)
return letra
def getchar():
s = ''
return msvcrt.getch().decode('utf-8')
print("\nWelcome to Key Pop It!")
opcion = int(input("\n Press 1 to play OR\n Press 2 for instructions"))
if(opcion == 1):
acum=0
while True:
letra2 = generarletra()
print(letra2)
key = getchar()
for s in range (0,2):
print("Segundos ", s)
time.sleep(2)
acum = acum + 1
if((key is not letra2) or (s == 2)):
print("su record fue de, ", acum)
break
elif(opcion == 2):
print("\n\nWelcome to key pop it!\nThe game is simple, the machine is going to generate a
random\nletter and you have to press it on your keyboard, if you take too\nlong or press the wrong
letter, you will lose.")
else:
print("Invalid option!")
PD: You need to run it with a console simulation in your IDE or directly from the console. msvcrt library won't work inside an IDE for some reason.
msvcrt.getch() is blocking, so you don't actually measure the time it took the user to press the key. The for loop starts after the user already pressed it.
also, time.sleep() is blocking, so the user will have to wait the sleep time even if he already pressed the key.
To solve the first problem you can use msvcrt.kbhit() to check if the user pressed on some key, and call msvcrt.getch() only if he did. This way msvcrt.getch() will return immediately after you call it.
To solve the second problem you can just use time.time() to get the start time of the round, and compare it to current time inside a loop. You can print how much time passed inside the loop also.
Here is the final code (with some extra naming and formatting changes):
import string
import random
import msvcrt
import time
MAX_TIME = 2
def get_random_char():
return random.choice(string.ascii_lowercase)
def get_user_char():
return msvcrt.getch().decode('utf-8')
print("\nWelcome to Key Pop It!")
option = input("\n Press 1 to play OR\n Press 2 for instructions\n")
if option == "1":
score=0
while True:
char = get_random_char()
print("\n" + char)
start_time = time.time()
while not msvcrt.kbhit():
seconds_passed = time.time() - start_time
print("seconds passed: {0:.1f}".format(seconds_passed), end="\r")
if seconds_passed >= MAX_TIME:
key = None
break
else:
key = get_user_char()
if key != char:
break
score = score + 1
print("\nsu record fue de, ", score)
elif option == "2":
print("""
Welcome to key pop it!
The game is simple, the machine is going to generate a random
letter and you have to press it on your keyboard, if you take too
long or press the wrong letter, you will lose.""")
else:
print("Invalid option!")
Timestamp-solution:
from time import time, sleep
start = time() # start time measuring by creating timestamp
def time_passed(start, duration):
"""tests if an amount of time has passed
Args:
start(float): timestamp of time()
duration(int): seconds that need to pass
Returns:
bool: are 'duration' seconds over since 'start'
"""
return start + duration <= time()
# Use as condition for while
while not time_passed(start, 5):
sleep(1)
# ... or if statements or <younameit>
if time_passed(start, 5):
print("Do something if 5 seconds are over")
So I have a code I'm working on to automatically play my alarms at the times I specify. It also is playing some city sounds to help me sleep and while playing those sounds I can't get the while loop to end to have the alarm sound to play.
I tried to bring the while loop into the alarm function I've created but that didn't work but I'm fairly certain it has something to do with my while loops. But I'm thinking a fresh pair of eyes might do this code some good.
'''
Title: This is an alarm that perfectly lines up with my sleep schedule
Author: Riley Carpenter
'''
from pygame import mixer
import time
import os
import sys
import random
snoozeorstop = " "
Currenttime = time.ctime()
Hours1 = int(Currenttime[11:13])
Minutes1 = int(Currenttime[14:16])
Seconds = int(Currenttime[17:19])
optionalsongs = ["Pink Floyd Time.wav","Alarm2.wav","Alarm3.wav","Alarm4.wav","Alarm5.wav","Alarm6.wav","Alarm7.wav","Alarm8.wav","Alarm9.wav","Alarm10.wav","Alarm11.wav"]
phrases = ["Wake up Riley!!!!","It's time to wake up it's time to wake up","HEEEEYYY WAKE UP","RILEY RILEY RILEY WAKE UP","1 2 3 4 5 6 7 8 9 it is time to wake up","Riley more alarms are to come UNLESS you get up","OH WHEN SHALL I SEE JESUS you wanna not hear this again? Wake up","I'm so tired of telling you to wake up just wake up","A friend of the devil is somehow who doesn't wake up","Babe babe bae wake up"]
def playsound(soundfile):
mixer.init()
mixer.music.load(soundfile)
mixer.music.play(-1)
def stopsound():
mixer.music.stop()
def alarm(hour,minute):
print("")
print("")
print(random.choice(phrases))
if Hours1 == hour and Minutes1 == minute:
stopsound()
playsound(random.choice(optionalsongs))
print("")
snoozeorstop = input("Do you want to stop the song? ")
if snoozeorstop == "stop":
stopsound()
citysounds = input("Do you want to play the soothing sounds of the city? ")
if citysounds == "y" or citysounds == "Yes" or citysounds == "Y" or citysounds == "yes":
playsound("Citys Night ambience sounds.wav")
else:
playsound("Beginningsound.wav")
amount = 0
print("This is how many second has passed since this alarm was turned on")
while Hours1 != 5 and Minutes1 != 0:
Currenttime = time.ctime()
print(amount)
Hours1 = int(Currenttime[11:13])
Minutes1 = int(Currenttime[14:16])
Seconds = int(Currenttime[17:19])
amount += 1
time.sleep(1)
alarm(5,00)
alarm(5,5)
alarm(5,10)
alarm(5,15)
alarm(5,20)
alarm(5,25)
alarm(5,30)
alarm(5,35)
alarm(5,40)
alarm(5,45)
alarm(5,50)
alarm(5,55)
alarm(6,00)
alarm(6,5)
alarm(6,10)
alarm(6,15)
alarm(6,20)
alarm(6,25)
Since the while loop is central to your program, why not write that piece of code first. When that works as intended you can add songlists etc.
As for checking for the time when the alarm should go off you might want to check out the datetime module which makes time calculations much easier. For example:
import datetime, time
start = datetime.datetime.now()
alarm = start + datetime.timedelta(seconds=5) # Set alarm time 5 seconds from now
while True:
now = datetime.datetime.now() # When is this?
print(now.strftime("%H:%M:%S")) # Print human readable time
if now > alarm: # Have I passed the alarm time?
print('Alarm') # Sound the alarm
break # Leave this loop
time.sleep(1)
I have this following code and am stuck in the while loop
I know there is a problem with the while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)): line.
Can anyone help please ?
nodes_with_scanner = []
wait_time = 60
while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)):
nodes_with_scanner = get_nodes_with_scanner_in_dps(self.node_names, scanner_id, username=self.users[0].username)
log.logger.debug("Number of pre-defined {0} scanners detected in DPS: {1}/{2}".format(scanner_type, len(nodes_with_scanner), len(self.node_names)))
if state == "create":
if len(self.node_names) == len(nodes_with_scanner):
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully created in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
elif state == "delete":
if len(nodes_with_scanner) < 1:
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully deleted in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
log.logger.debug("Still waiting on some {0} pre-defined scanners to '{1}' in DPS; sleeping for 1 minute before next check".format(scanner_type, state))
time.sleep(60)
You are asking if the current time is smaller than the current time plus a delta. Of course that's going to be true each and every time, the future is always further away into the future.
Record a starting time once:
start = datetime.datetime.now()
while datetime.datetime.now() < start + datetime.timedelta(minutes=wait_time)):
If wait_time doesn't vary in the loop, store the end time (current time plus delta):
end = datetime.datetime.now() + datetime.timedelta(minutes=wait_time))
while datetime.datetime.now() < end:
It may be easier to just use time.time() here:
end = time.time() + 60 * wait_time
while time.time() < end:
You use datetime.datetime.now() in your while loop, what means each iteration you check if the time now is lower then the time now + delta.
That logically wrong, because it will be True forever as the time now will be always lower than the time now plus delta.
You should change it to this:
time_to_start = datetime.datetime.now()
while datetime.datetime.now() < (time_to_start + datetime.timedelta(minutes=wait_time)):
print "do something"
I am trying to create a stopwatch that starts and stops through the user pressing the enter. Once to start and again to stop. The start works perfectly but the stopping section is not working. I've tried creating a variable called stop that is like so:
stop = input("stop?")
But it's still not working.
import time
def Watch():
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1
def whiles():
if start == "":
Watch()
if start == "":
return Watch()
def whiltr():
while Watch == True:
stop = input("Stop?")
#Ask the user to start/stop stopwatch
print ("To calculate your speed, we must first find out the time that you have taken to drive from sensor a to sensor b, consequetively for six drivers.")
start = input("Start?")
start = input("Stop")
whiles()
Perhaps all you need is something simple like:
import time
input('Start')
start = time.time()
input('Stop')
end = time.time()
print('{} seconds elapsed'.format(end-start))
Should probably use the time function instead of
def Watch():