I want to print the current time on screen in hours and minutes that updates automatically without making a new line, as well as print another line with the seconds that also updates automatically on a second line. Thanks in advance! This is what I have so far:
import time
from datetime import datetime
while True:
now = datetime.now()
current_time = now.strftime("%I:%M %p")
current_second = now.strftime("%S")
print("\r" + "Clock: ", current_time, end= ' ')
print("\r" + "\n" + "Seconds: ", current_second, end=' ')
time.sleep(1)
This is what the output looks like: Output
The seconds out like they should, but the time does not
Combining #Rhuamer's answer with your code, you can do something like:
import subprocess
import sys
import time
from datetime import datetime
clear = "cls" if sys.platform == "win32" else "clear"
while True:
now = datetime.now()
current_time = now.strftime("%I:%M %p")
current_second = now.strftime("%S")
print(f"\rClock: {current_time}", flush=True, end="\n")
print(f"Seconds: {current_second}", flush=True, end="")
time.sleep(1)
subprocess.run(clear, shell=True)
Try clearing the console with a clear method. Define it like this:
from os import system, name
if name == "nt":
clear = lambda: system("cls")
else:
clear = lambda: system("clear")
and then just call it every loop
The heart of this question is based around how to clear the console and there are a number of good answers here Clear terminal in Python and I recommend you explore it. The other part of the question deals with writing on multiple lines and so I feel this is not quite a duplicate.
I think the easiest way to get what you seek might be to use an f-string and simply do:
import time
from datetime import datetime
while True:
now = datetime.now()
current_time = now.strftime("%I:%M %p")
current_second = now.strftime("%S")
print(f"\033cClock: {current_time}\nSeconds: {current_second}")
time.sleep(1)
If that does not quite work correctly, there are other more slightly extended escape codes you can explore such as \033c\033[3J. I have tested the \033c on a few terminals with success though.
If after reviewing that other question, you feel this is a duplicate, just let me know and I will remove this answer and you can close the question.
Related
I need my code to stop and wait until the next day. The time does not matter, I just need it to continue when the date changes.
currentDate = datetime.datetime.now()
future = datetime.datetime(currentDate.year, currentDate.month,
(currentDate.day + 1))
time.sleep((future-currentDate).total_seconds())
The code pauses but does not continue after
Two options here with comments.
First do imports
import datetime
import time
one uses a while loop - probably not a good solution but highlights one way to wait for a condition to be met.
def loop_until_tomorrow():
""" Will use a while loop to iterate until tomorrow """
#get current date
currentDate = datetime.datetime.now().date()
# loop attempts
times = 0
# this will loop infiniatly if condition is never met
while True:
# increment by one each iteration
times += 1
#get date now
now = datetime.datetime.now().date()
if currentDate != now:
# return when condition met
print("\nDay has changed")
return
else:
# print attempts and sleep here to avoid program hanging
print(f"Attempt: {times}".ljust(13) + " - Not tomorrow yet!", end="\r")
time.sleep(5)
the other - sleeps for the amount of seconds from now till tomorrow
def sleep_until_tomorrow():
"""wait till tomorrow using time.sleep"""
#get date now
now = datetime.datetime.now()
#get tomorrows date
tomorrow_date = now.date() + datetime.timedelta(days=1)
#set to datetime
tomorrow_datetime = datetime.datetime(year=tomorrow_date.year, month=tomorrow_date.month, day=tomorrow_date.day, hour=0, minute=0, second=0)
#get seconds
seconds_til_tomorrow = (tomorrow_datetime-now).total_seconds()
#sleep
time.sleep(seconds_til_tomorrow)
You can use schedule for that purpose, which will give you the flexibility to refactore the code when needed without having to write a chunck of code.
from schedule import every, repeat, run_pending
import time
#just to give you the idea on how to implement the module.
#repeat(every().day.at("7:15"))
def remind_me_its_a_new_day():
print("Hey there it's a new day! ")
while True:
run_pending()
time.sleep(1)
i'd like to know how to sync datetime with system time in real time. what i mean is the code always prints the same hour same minute and same seconds if i loop the code. this is my code
from datetime import datetime
import os
from time import sleep
def clear():
os.system('cls')
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
while True:
time = print("Current Time =", current_time)
sleep(1)
clear()
i need help for this thx!
You are currently creating the date-time object only once with the line. This means the time is only looked up once and then that value is stored in the variable.
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
All you need to do is move those two lines into your loop. That way, the time is looked up on each loop iteration and you get new values. The modified code:
from datetime import datetime
import os
from time import sleep
def clear():
os.system('cls')
while True:
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
time = print("Current Time =", current_time)
sleep(1)
clear()
Thanks for the answer! i also modify the code a little bit to make it a little bit better
from datetime import datetime
from time import sleep
while True:
now=datetime.now()
current_time=now.strftime("%H:%M:%S")
time=print("Current Time : ", current_time, end=\r)
sleep(1)
I'm trying to write a program to remind a user to take breaks. Here is the code:
import datetime
import os
from playsound import playsound
import time
# current_time = datetime.datetime.now()
# print(current_time)
running = True
while running:
current_time = datetime.datetime.now()
new_time = datetime.datetime.now()
# print(current_time)
breaktime = datetime.timedelta(
days=0,
hours=0,
minutes=1
)
times = datetime.timedelta(seconds=5)
time.sleep(6)
new = current_time + times
if new_time == new:
print("hello")
playsound('Take_Flight.mp3')
running = False
break
The program does not play the sound Take_Flight.mp3 and it does not print hello.
How can I make it work?
I think the reason your alarm does not ring is because of the break statement at the bottom line of your code. The while loop simply ends without looping over and over again as you intended. I believe if you remove that your code will work. As an alternative to what you wrote you can also make the program wait for 5 min and then ring without getting the current time:
while True
time.sleep(300000)
print("hello")
playsound('Take_Flight.mp3')
I'm trying to write a Python program that reproduces a sound every certain hour, but it doesn't really work. When I test the code and the specified time comes, it will keep repeating the sound forever.
Here is the code:
import os
from datetime import datetime
now = datetime.now()
currentHour = now.hour
currentMin = now.minute
#I also tested with if but it didn't work
while currentHour==15 and currentMin==33:
os.system("aplay /home/pi/sound.wav") #Plays the sound thru aplay
Your logic is wrong.
First of all, the while loop will most likely end in the first iteration and you want the program to continue till you tell it to.
In addition to that, you don't update the now variable inside the loop, which is basically a bad idea.
For example, this code will continue running and when it is 15:33, a sound will be played only once.
myHour = 15
myMin = 33
is_played = False
while True:
now = datetime.now()
currentHour = now.hour
currentMin = now.minute
if currentHour == myHour and currentMin == myMin and not is_played:
is_played = True
os.system("aplay /home/pi/sound.wav")
if currentHour != myHour or currentMin != myMin:
is_played = False
Xiaotian Pei suggested a great idea, to efficiently use your CPU resource, lets use the Timer module:
def to_play_sound(hour, min):
now = datetime.now()
currentHour = now.hour
currentMin = now.minute
if currentHour == hour and currentMin == min and not is_played:
is_played = True
os.system("aplay /home/pi/sound.wav")
if currentHour != myHour or currentMin != myMin:
is_played = False
while True:
t = Timer(30.0, to_play_sound, [15, 33])
t.start()
J.F. Sebastian has also suggested a great idea:
import datetime
import subprocess
while True:
now = datetime.now()
# compute `deadline`
while True:
deadline = now.replace(hour=hour, minute=min)
if deadline > now:
break
else:
deadline += datetime.timedelta(1)
sleep_until(deadline) # sleep
subprocess.check_call(['aplay', '/home/pi/sound.wav']) # play the sound!
Read how sleep_until was implemented here.
It's a complement to #bshuster13 's answer.
What you need is actually a timer. Using a busy loop and detect if it's the right time to do something is not a good idea. Take a look at Timer in python. I think you will come up with a better solution.
I'd like to schedule a repeated timed event in python like this:
"at time X launch function Y (in a separate thread) and repeat every hour"
"X" is fixed timestamp
The code should be cross-platform, so i'd like to avoid using an external program like "cron" to do this.
code extract:
import threading
threading.Timer(10*60, mail.check_mail).start()
#... SET UP TIMED EVENTS HERE
while(1):
print("please enter command")
try:
command = raw_input()
except:
continue
handle_command(command)
Create a dateutil.rrule, rr for your schedule and then use a loop like this in your thread:
for ts in rr:
now = datetime.now()
if ts < now:
time.sleep((now - ts).total_seconds())
# do stuff
Or a better solution that will account for clock changes:
ts = next(rr)
while True:
now = datetime.now()
if ts < now:
time.sleep((now - ts).total_seconds() / 2)
continue
# do stuff
ts = next(rr)