How to show text when certain time comes - python

How to show text when certain time comes
Such as when the time to 0:30:0 will display the text
import time
def countdown(time_sec):
time_msec = time_sec*10
while time_msec:
mins, secs = divmod(time_msec, 600)
secs, msecs = divmod(secs, 10)
timeformat = "{:02d}:{:02d}.{:01d}".format(mins, secs, msecs)
print(timeformat, end='\r')
time.sleep(1/10)
time_msec -= 1
print("stop")
countdown(61)

I can show you an example I coded some time ago, which displays a message every time the clocl hits 30 seconds.
import datetime
import time
# set the target time to 30 seconds
target_seconds = 30
while True:
# get the current time in seconds
current_seconds = datetime.datetime.now().time().second
# check if the current time matches the target time
if current_seconds == target_seconds:
print("It's time!")
# wait for 1 second before checking the time again
time.sleep(1)
you should be able to adapt it for your needs. Basically you do an if cluase that checks if your target time has come.

We can eliminate that remote possibility of 'skipping' by making clock independent. A modified version of #fallouthase :
import datetime
import time
target_seconds = 30
def print_str(time):
if time==target_seconds:
print("Its time")
def time_call(time):
print(current_seconds)
while True:
current_seconds = datetime.datetime.now().time().second
time_call(current_seconds)
print_str(current_seconds)
time.sleep(1)

Related

i wanted to write a code that executes a function at a specific time but

i wanted to write a code that executes a function at a specific time but...
it keeps running the code immediately i tried 6 different ways to code it but they all failed
i will past the code below
first i tried
import schedule
import time
import m5
def run_f5():
m5.runF5()
schedule.every().day.at("02:05").do(run_f5)
while True:
schedule.run_pending()
time.sleep(1)
#this code was supposed to run 5 mins from now but it ran immediately
then i tried
import datetime
import time
import m5
while True:
current_time = datetime.datetime.now()
if current_time.hour == 2 and current_time.minute == 12:
m5.runF5()
time.sleep(60)
#this code was supposed to run 5 mins from now but it ran immediately
then i tried
import datetime
import time
import m5
while True:
current_time = datetime.datetime.now()
if current_time.hour == 2 and current_time.minute == 24:
m5.runF5()
time.sleep(60)import datetime
import time
import m5
while True:
current_time = datetime.datetime.now()
if current_time.hour == 2 and current_time.minute == 24:
m5.runF5()
time.sleep(60)
same result the code ran immediately then i tried
import datetime
import time
import m5
# Get the current time
current_time = datetime.datetime.now()
# Create a datetime object for the desired time
desired_time = datetime.datetime(current_time.year, current_time.month, current_time.day, 2, 59)
# Check if the desired time has passed for today
if desired_time < current_time:
# If it has, set the desired time to tomorrow
desired_time += datetime.timedelta(days=1)
# Calculate the time difference between the current time and the desired time
time_diff = desired_time - current_time
# Sleep for the time difference
time.sleep(time_diff.total_seconds())
#Run your function
m5.runF5()
same the code ran immediately then i tried
import datetime
import time
import m5
while True:
current_time = datetime.datetime.now()
if current_time.hour == 3 and current_time.minute == 30:
m5.runF5()
break
time.sleep(60)
i tried the followed 3 codes but failed each time
import datetime
import time
import m5
current_time = datetime.datetime.now()
# Create a datetime object for the desired time
desired_time = datetime.datetime(current_time.year, current_time.month, current_time.day, 3, 40)
# Check if the desired time has passed for today
if desired_time < current_time:
# If it has, set the desired time to tomorrow
desired_time += datetime.timedelta(days=1)
# Calculate the time difference between the current time and the desired time
time_diff = desired_time - current_time
# Sleep for the time difference
time.sleep(int(time_diff.total_seconds()))
#Run your function
m5.runF5()
then
import datetime
import time
import m5
# Create a datetime object for the desired time
desired_time = datetime.datetime(current_time.year, current_time.month, current_time.day, 3, 56)
while True:
current_time = datetime.datetime.now()
if current_time >= desired_time:
break
time.sleep(1)
# Run your function
m5.runF5()
import schedule
import time
import m5
def run_at_specific_time():
m5.runF5()
# Schedule the function to run every day at 04:10 AM
schedule.every().day.at("12:00").do(run_at_specific_time)
while True:
schedule.run_pending()
time.sleep(1)
plz help i have ran out of ideas and have no clue why any of the above run at once and not at the specific time
i am importing the code from a separate file maybe that is causing some issues

if statement doesn't work in while loop with time lib python

Here is the code (only this):
import pytz
from time import sleep
from datetime import datetime
dt_format = "%H:%M"
tz = pytz.timezone('Asia/Riyadh')
jt = datetime.now(tz)
time_now = (jt.strftime(dt_format))
time = time_now.replace(":","")
timed1 = (int("1530")) #the time in 24h format
while True:
#print('azan on')
if timed1 == time_now:
print(time_now)
print(timed1)
print ("its the time")
sleep (90)
I tried to keep the format normal (15:30) but still the same.
(replace) not required you can delete if so.
You just have to update the time and put it in the loop and it will work , thanks to #MatsLindh (check comments)

How to run my computer's time setter as a silent backgound PID?

I guess my computer's battery of bios got dead; consequently the system time is never accurate, it is sometimes stuck at 1 PM with a faulty date, so I came up with this code with the idea of fetching universal time from an api and setting my computer's time accordingly.
My problem is how to make my code run in the background without printing any ping results to the screen or showing anything. I need it to function as a PID and keep alive as long as the computer is on.
PS: I am using Windows 7
from json import loads
from urllib.request import urlopen
import logging
from win32api import SetSystemTime
from datetime import datetime
from time import sleep
import re
from os import system
while True:
# connection is dead with 1, connection is alive with 0
connection_is_dead = 1
while connection_is_dead != 0:
connection_is_dead = system('ping -n 1 google.com')
logging.basicConfig(level=logging.INFO)
logging.disable(level=logging.INFO) # logging off
logging.info('Connection is up...')
try:
with urlopen("http://worldtimeapi.org/api/timezone/africa/tunis") as time_url:
text = time_url.read()
logging.info('Time api imported...')
mytime_dict = loads(text)
time_now = mytime_dict['datetime']
logging.info(time_now)
time_stamp = re.compile(r'(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d+)[+|-].*')
time_match = list(map(int, re.match(time_stamp, time_now).groups()))
# winapi32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds )
dayOfWeek = datetime(*time_match[:3]).weekday()
SetSystemTime( *time_match[:2],dayOfWeek, *time_match[2:6], 0)
logging.info('Time updated successfully...')
#system('exit')
sleep(1800) # 3O min / reset time every 30 min
except:
logging.error('Time was not updated due to an unexpected error... ')
#system('exit')

How to record stream for exactly 30 seconds using python-vlc?

I'm trying to record an RTP stream via python-vlc for exactly 30 seconds but the output file is sometimes less than or greater than my desired video length.
Note: I tried using ffmpeg, but it can't properly decode the stream hence the decision to use python-vlc.
This is my code:
import vlc
import time
vlcInstance = vlc.Instance("--demux=ts")
player1 = vlcInstance.media_player_new()
media1 = vlcInstance.media_new("rtp://239.194.115.71:5000")
media1.add_option("sout=file/ts:sample.mpg")
limiter = 0
player1.set_media(media1)
player1.play()
time.sleep(1)
while player1.is_playing():
if limiter > 30:
player1.stop()
media1.release()
break
limiter = limiter + 1
time.sleep(1)
What possible method can I use to always record the stream for exactly 30 seconds?
I used opencv-python to get the current frame count and fps of the output file and used it to compute for the video length.
import vlc
import time
import cv2
import os.path
vid_len = 0
vlcInstance = vlc.Instance("--demux=ts")
player1 = vlcInstance.media_player_new()
media1 = vlcInstance.media_new("rtp://239.194.115.71:5000")
media1.add_option("sout=file/ts:sample.mpg")
player1.set_media(media1)
player1.play()
#checks if the length of the output exceeds 30 seconds
while vid_len < 30:
time.sleep(1)
#checks if the file exists and not empty
if os.path.isfile('sample.mpg') and (os.path.getsize('sample.mpg') > 0):
video_file = cv2.VideoCapture('sample.mpg')
frames = int(video_file.get(cv2.CAP_PROP_FRAME_COUNT))
fps = (video_file.get(cv2.CAP_PROP_FPS))
vid_len = frames/fps
player1.stop()
media1.release()

Random.randrange() attached to a button

I need to make a GUI with a button where the button will appear in a random interval of time (from 1 to 10 seconds). I know I need to use the random.randrange() command but I dont know how to.
This is my code so far:
#Importere værktøjer
from tkinter import*
import datetime
import time
import os
import datetime
import random
#Tiden
start = time.clock()
finish = time.clock()
elapsed_time = finish - start
t = datetime.datetime.now()
#Definitioner
def myClickMe1():
label1["text"]='{0:.2f}'.format(elapsed_time)
print('{0:.2f}'.format(elapsed_time))
return
#rod defineres
window=Tk()
#Vinduet
window.geometry("700x800")
window.title("Reaktionshastighehs test")
#Labels
label1=Label(window, text="Klik nu!")
#indstillinger til objekter
button1=Button(window, text="Klik her!", command=myClickMe1)
#Placering af objekter
button1.place(x=330, y=460)
label1.place(x=335,y=500)
print(t.second/1000)
I wany my button1 to appear at a random time from 1 to 10 seconds. Can anyone help me plsease?
Thanks
Kasper
Tkinter has an after method that you can run on your root window that will call a function after an amount of time (in milliseconds).
Random has a randint() method that can return an integer between two numbers.
So, call after and pass a randint between 0 and 10 seconds, then call the function to create the Button:
def placeButton():
Button(window, text='Click').pack()
window.after(random.randint(0,10000), placeButton)

Categories

Resources