Add another hour when running python script on 2nd iteration

Issue

I have a Python script that uses the datetime, timedelta, and selenium modules.
The script goes to a website, enters the current time (using datetime), and adds the number that the user inputted onto the current time (using timedelta).

I also have a loop going. But I want to make sure that when the script is on its 2nd loop, it will add double the user input.

(E.G: user enters a 2, the script will enter a 2 onto the current time’s hour. Then loops again, but this time adds a 4 to the current time’s hour.)

Does anyone know how I could implement this idea? It will be very useful for my project, thanks.

Code:

import undetected_chromedriver as uc
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime, timedelta
import time

hr_input = int(input('how many hours to add?: ')
amount_loops = int(input('how many times to loop?: ')

for i in range(amount_loops):
        time.sleep(2)
        adding = (datetime.now() + timedelta(hours=int(hr_input))).strftime("%H:%M")
        wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="input-1"]/input'))).send_keys(adding + Keys.ENTER)
        time.sleep(2)

Solution

assuming you want to multiply it by 2 each time, you can use the i variable and multiply the by 2**i

  1. so first time 2**0 = 1 so no effect
  2. second time 2**1 = 2 so times 2
  3. third time 2**2 = 4 etc. etc.

i.e

    adding = (datetime.now() + timedelta( hours=2**i*int(hr_input) )).strftime("%H:%M") 

Answered By – Xinurval

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.