'datetime expected float, got string

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.



Solution 1:[1]

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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris
Solution 2 Adrian Ang