How to Display Time (not static) in python? - python

Alright,the problem is i'm trying to build a personal assistant with my amateur skills.
I want to display the time which should be running and not be static.

This is what you wanted ? create a endless loop (Since you didn't mention in what situation the loop will end, I assume it will run infinitely until you manually end it) and print() with end='\r' (replace prev print) and pause and refresh every second
import time
import datetime
while True:
now = datetime.datetime.now()
print(f"Current Date and Time: {now} ", end='\r')
time.sleep(1)

Related

Is there a way to execute a part of a PYTHON script only at a given time

I write a bot that should automatically register me for an exam.
The bot should be faster than a human especially the to last lines(will add them below)
I will open the python script a few minutes before the time it need to be executed.
I am looking for a solution to the following problem:
My code (its in production I will change the username and password variable to not be plaintext).
I will also wrap it in functions.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from datetime import datetime
import time
path = "my_path"
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=my_user-data-dir")
driver=webdriver.Chrome(path, chrome_options=options)
time_now = datetime.now()
driver.get("linkt_to_website")
login = driver.find_element_by_class_name("Login")
login.click()
user = driver.find_element_by_id("username")
user.send_keys("my_username")
pwd = driver.find_element_by_id("password")
pwd.send_keys("my_password")
lgnbtn = driver.find_element_by_id("loginbutton")
lgnbtn.click()
driver.get("website linkt to the page with the button to register for my exam")
time.sleep(1)
toggle = driver.execute_script("js function to trigger dropdown menue")
# until here it does not make a difference how much time the bot need
until here everything works fine
the goal is that the bot logs in and wait until a predefined time(hour, minutes, seconds, milliseconds)
but now I have a question:
# the two lines below are the most important
anmed= driver.find_element_by_xpath("register button xpath ").click()
last_btn= driver.find_element_by_xpath("are you sure register button ").click()
The two button I want to trigger in the two lines above will appear at a given time so I need to make a function to trigger the two lines when its for example exactly 10:00:00 in the morning.
I hope this question makes sense.
The main goal is to start the script a few minutes before "10:00:00"AM it logs in and wait until 10AM and as accurately as possible execute the two last lines to actually register for my exam.
Thank you in advance:)
If you want to pause your code until a particular time, then you essentially want your code to sleep for N seconds where N has been calculated to land at the time you want.
import time
#Time right now in seconds from epoch.
c = time.time()
#Time at 6:10 PM today from epoch.
n = time.mktime(time.strptime('2021:02:09-18:10:00','%Y:%m:%d-%H:%M:%S'))
#Pause code for seconds until it reaches 6:10 PM today.
sleep(n-c)
#Run code after pausing.
I am EST time, so things might be different for you.
Are you sure you don't need to reload the page when for the button to become active? If not, this is a quick and dirty way to use time and datetime to check if the moment is right, and if not, wait (1 second) and try again later. You could check every 0.1 seconds if you think that would be more successful.
You might also want to use a "try" block incase the sync between your computer time and server time don't agree and so you look for a button that does not exist yet and trigger an error thus disrupting your code.
import datetime
import time
trigger_time = datetime.datetime(2021, 2, 9, 22, 0, 0) # Tonight at 10PM
while True:
now = datetime.datetime.now()
if now >= trigger_time:
try:
# RUN CODE
except WHATEVEREXCEPTION_SELENEIUM_THROWS_FOR_MISSING_ELEMENTS:
pass
if code_success:
break
else:
time.sleep(1) # Wait for 1 second

Is there any way to find boot up time of any windows Application?

Suppose I am using VLC Player and I want to calculate the time it takes to boot using python , is there any way?
I have tried winium automation , but elements load too slowly. I want to get boot up time of my application and it boots in 4-5 seconds , whereas winium usually takes more than that to find the location of element.
If anyone can suggest any better way via backend automation, please comment.
If i understood you right, you need to find time from moment you executed the app to the moment the window appears. You can do that with pygetwindow library. Here's the code:
import pygetwindow as pw
import time
# here's code that executing the program, but i just put comment
start = time.time()
while 1: # waiting until window appears
# getWindowsWithTitle method returns empty list if it didn't found any windows with this name
if pw.getWindowsWithTitle('VLC'): #if it founds the window, loop will break
break
stop = time.time()
result = stop - start # result is time in seconds (type float)
EDIT
You also can detect start of application by checking if amount of windows changed.
import pygetwindow as pw
import time
starting_amount = len(pw.getAllWindows()) # amount of windows
# here's code that executing the program, but i just put comment
start = time.time()
while 1: # waiting until window appears
if len(pw.getAllWindows()) > starting_amount: #if amount of windows is bigger than it was before we executed the program
break
stop = time.time()
result = stop - start # result is time in seconds (type float)
This should work with LD Player

How to update a timestamp taken from server?

I have a very simple Python script in which I'm trying to print an updated timestamp (taken from a server by APIs) every n seconds.
After importing a custom module (FinexAPI) and the time module:
import FinexAPI
import time
and setting up the variable to get the server timestamp:
ticker = FinexAPI.ticker()
when = float(ticker['timestamp'])
if I perform:
print when
I'm getting the timestamp up to date. If I perform it again, I can see a new updated timestamp. Untill now there's no problem at all.
Now let's suppose I need to perform an "updated timestamp print" every 5 seconds:
def getNewTimestamp():
print when
time.sleep(5)
while True:
getNewTimestamp()
But with this code I'm getting the same timestamp every 5 seconds. I suppose the problem is that I'm defining when outside the getNewTimestamp function, so it basically keeps printing the same non-updated timestamp. But even if I define it inside the function I still get no update on the timestamp.
Another thing I'm thinking about is that while loop is not the best choice in this scenario, but that would be another story (I think...). Can someone help me figuring out what am I doing wrong and what is the best way to obtain and print the updated timestamp every 5 seconds?
You have to call the API in the loop:
def getNewTimestamp():
ticker = FinexAPI.ticker()
when = float(ticker['timestamp'])
print when
while True:
getNewTimestamp()
time.sleep(5)

How to use datetime to calculate duration and stop time?

I'm using Python 2.7 and want to use the datetime functions to calculate a user defined time to run a small pump. I know I'm missing something obvious but I've searched until I can't see straight. I have a textCtrl that the user will enter the minutes he wants the pump to run. Then a button click will start the scheduler and check to see if it's time to turn off the pump:
def timedPump(val):
now = datetime.datetime.now()
timeOff = now + datetime.timedelta(minutes=int(val))
if timeOff > now:
print 'pumpOn'
else:
print 'pumpOff'
return True
The problem is that datetime.datetime.now() updates everytime. How do I make it so that now = the time that the button was clicked?
This would be my solution to the problem:
from time import sleep
def pumpcheck(timer_in_minutes):
time_clicked = datetime.datetime.now()
now = time_clicked
timeDiff = datetime.timedelta(minutes=int(timer_in_minutes))
while (time_clicked + timeDiff > now):
print 'pumpOn'
now = datetime.datetime.now()
sleep(2)
print 'pumpOff'
It saves the time when the button was pushed and then checks in a loop, if the time is rfeached, if not, it update the current time, says pump is still on and sleep for a little while to not bloack cpu recources. When the time is reached, it says pumpoff
There is some information missing as to how timedPump is evaluated. I guess it's a simple loop.
What needs to happen is there have to be two functions, one that sets a turnOff-time and one that evaluates weather to turn on / off the pump.
This can be implemented as two methods of a class:
class PumpControl(object):
def setTime(self, val):
now = datetime.now()
self.timeOff=now + timedelta(minutes=int(val))
print 'pumpOn'
def checkTime(self):
if self.timeOff < datetime.now():
print 'pumpOff'
This way you would create a PumpControl object and then repeat checkTime:
controller = PumpControl()
#inside your loop
controller.checkTime()
#when you want to set the time
controller.setTime(val)
This should work across threads as well, so you can have one thread repeating and another asking for the time.
This sounds like something outside the scope of a single function. Either split the logic into two functions, or use a class to preserve start_time

print python counter of GPIO pin output at set intervals

I'm having a problem with a task i'm doing with an anemometer that works using a switch every revolution. The task is using a raspberry pi therefore the language is in python.
What I am trying to do is print a counter value every 10 seconds. However I don't want it to be a delay where nothing happens during the 10 second wait. Basically I want the number of times a switch is pressed in 10 seconds printed to me every 10 seconds.
Sorry if that was vague any extra info needed just ask.
While True:
stuff = dio.readU8(portB)
dio.write8(portA, stuff)
if stuff == 192:
print ('on')
else:
print ('off')
This is what it currently does simply constantly print its state either on or off I havn't yet implemented a counter as I am unsure the way it works in python and am wondering if it is similar to other languages i'm new to python I only usually use Java. The above code works even though values may look weird.
You could use the time module to watch the time, put it in at the end of the event catching code to see if 10+ seconds has passed.
something like...
import time
last_time = time.time()
#start of event catching loop
if time.time() - last_time >= 10
print buttonCountVariable
last_time = time.time()

Categories

Resources