Home > Back-end >  datetime expected float, got string
datetime expected float, got string

Time:05-17

I'm trying to make a pyautogui script that adds the users input to the current time using the datetime/timedelta module. I want the pyautogui part to use typewrite and type out the result to a website (current time user input) new_time = now xtime.

My code:

import datetime
from datetime import timedelta

xtime = (input("enter a time in numbers: "))

now = datetime.datetime.now()
now   timedelta(hours=xtime)
new_time = now   xtime
pyautogui.typewrite(new_time)
pyautogui.press('enter')

I get these error messages

Expected type 'float', got 'str' instead

Unexpected type(s):(str)Possible type(s):(timedelta)(timedelta)

Please can someone help me. Thanks.

CodePudding user response:

The error is fairly self-explanatory. When you construct an object of type datetime.timedelta, it's expecting an argument of type float. The input function returns a string, though.

Try:

xtime = float(input("enter a time in numbers: "))

Your indentation also appears to be off, which will cause errors in Python.

CodePudding user response:

timedelta() requires hours to be a number, so I've converted it to an integer. Also I've formatted the time using .strftime() to make it more readable.

Try and see if these works:

import datetime
from datetime import timedelta

xtime = input("enter a time in hours: ")

now = datetime.datetime.now()
new_time = (now   timedelta(hours=int(xtime))).strftime("%Y-%m-%dT%H:%M:%S")
print(new_time)
pyautogui.typewrite(new_time)
pyautogui.press('enter')

Output:

enter a time in hours:  2
2022-05-16T22:45:49
  • Related