datetime expected float, got string - python

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.

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.

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

python - how do I find two desired integer values in a variable?

I'm in the process of learning how to code in Python and have been doing numerous tasks to help solidify info.
I had 1 issue - I am creating code that will take the date (dd/mm/yyyy) and then the program will validate the data (i.e checking if there are errors in the field and if so, naming the error type; if no errors are found, the user is told the input was correct) - just some data validation practise.
Where I'm getting stuck is just assigning the variables - I have typed and tested the day and year correctly but I cant manage to get the 4th and 5th integer of the variable date for the month variable.
Here is my code that I am first producing to make sure the integers I will be working with are correct:
date = input("Please enter the date in format dd/mm/yyyy: ")
valid_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-'
#defines where to locate day in user input
dayDate = str(date)[:2]
# could also be written as dayDate = str(date)[:-8]
#defines where to locate month in user input
def month(date):
return date[(len(date)//2)]
finalMonth = month(date)
#defines where to locate year in user input
yearDate = str(date)[-4:]
print(yearDate)
print(finalMonth)
print(dayDate)
From this code, the variables yearDate and dayDate present me with the values I want but the finalMonth is where i'm getting stuck. I've looked all over Google but can't seem to find the solution. If you do know how to solve my issue, I would really appreciate it if you could send the proper way to go about this and why you did what, as I am still kind of a newb in Python :)
I know the error is the function I've created for finding the month values, but that's precisely where I need help.
Thank you!
EDIT:
Sorry! I am new to Stack overflow so I didn't know.
so the code:
def month(date):
return date[(len(date)//2)]
finalMonth = month(date)
print(finalMonth)
returns the output '/' but what I am trying to get is for example you input '26/01/2021' and the variable finalMonth will give '01' - this code produces '/'. I am not sure what method should be used to get the month value.
you can use split() to create a list from input as below
date = input("Please enter the date in format dd/mm/yyyy: ")
valid_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-'
#defines where to locate day in user input
day, month, year = date.split("/")
print( day, month, year )
The quick answer to your error you were having is change
date[(len(date)//2)] to date[3:5]
After your clarification, I put together an example showing how you can handle error checking. :)
import datetime as dt
# the -> is to hint at the type of variable this function will return, this is not needed, but good practice
def get_date_from_user() -> dt.datetime:
# This will keep looping until correct gets changed to True
correct = False
while correct is False:
user_input = input("Please enter the date in format dd/mm/yyyy: ")
try:
# This part can be done in a lot of ways, I did it this way to demonstrate a condensed way and type conversions
date = dt.datetime(int(user_input[-4:]), int(user_input[:2]), int(user_input[3:5]))
correct = True # If the datetime was made successfully, set the loop to TRUE to escape
except ValueError as err:
print(err)
return date
date = get_date_from_user()
print(f'Day: {date.day} Month: {date.month} Year: {date.year}')
For handling dates though I highly recommend checking out Pendulum. With it you could do something like this:
import pendulum
date = pendulum.parse(input("Please enter the date in format dd/mm/yyyy: "))
dayDate = date.day
finalMonth = date.month
yearDate = date.year
It will throw an error if it cant parse what they typed in as well. If you wrap it in a Try and Except cause you can catch that too like below:
Python error handeling
import pendulum
try:
date = pendulum.parse(input("Please enter the date in format dd/mm/yyyy: "))
except ValueError as err:
print(err)
dayDate = date.day
finalMonth = date.month
yearDate = date.year

Invalid Token and if statement not working

This is my first time programming in Python and I am not too sure what I am doing wrong.
I am simply trying to print what the hour (time) is in words however I get the error "SyntaxError: invalid token" when I set the if statement to check
if current_hour == 05:
and when I change the 05 to 5 the If Statement simply does nothing.
This is my code:
import time
current_hour = time.strftime("%I")
print(current_hour)
if current_hour == 05:
print("Five")
Thank you!
current_hour is a string. For this to work you need the following:
import time
current_hour = time.strftime("%I")
print(current_hour)
if current_hour == '05':
print("Five")
or this:
import time
current_hour = int(time.strftime("%I"))
print(current_hour)
if current_hour == 5:
print("Five")
time.strftime returns a string like described in doc:
Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.
To compare in an if-statement you need to have the same datatype, so either convert the result to int or compare with a string like "05"
If you are not sure, which datatype is returned, you can check by using the type() method:
>>> print(type(current_hour))
<class 'str'>

How to set the microsecond to zero if not set by the user using Python datetime?

I am trying to take in a user input, and create a time object from that string. Something like this:
import datetime
user_input = '14:24:41.992181'
time = datetime.datetime.strptime(user_input, '%H:%M:%S.%f').time()
However, lets say if the user_input was '14:24:41', then I get a format error, which is understandable. What I want to do is for such an input, the microsecond precision for the time object would be set automatically to 000000. I noticed something similar is done for timezones using %z, and its built into the strptime() method.
What is the ideal way to do this?
you can use try/except and handle the case when user input does not match the format string
import datetime
user_inputs = ['14:24:41.992181','14:24:41']
for user_input in user_inputs:
try:
dt = datetime.datetime.strptime(user_input, '%H:%M:%S.%f')
except ValueError:
dt = datetime.datetime.strptime(user_input, '%H:%M:%S')
print(dt.strftime('%H:%M:%S.%f'))
output
14:24:41.992181
14:24:41.000000
You could run a simple check on the length of the input string, assuming you are expecting standardized inputs.
user_input = '14:24:41'
if len(user_input) == 8:
user_input += '.000000'
time = datetime.datetime.strptime(user_input, '%H:%M:%S.%f').time()

Python 2.7 - Add user inputed number to current time?

So basically I need to add a number that the user inputs, I'm just using raw_input, and I want to add that number, in minutes, to the current time.
So:
breakTime = int(raw_input("How long do you want to have a break for?"))
And I want to add whatever they type to
datetime.datetime.now()
Is this possible?
Thanks :)
You can use a datetime.timedelta for that:
import datetime
minutes = int(raw_input("break time"))
dt = datetime.timedelta(minutes = minutes)
later = datetime.datetime.now() + dt

Regex is not validating date correctly

def chkDay(x, size, part):
dayre = re.compile('[0-3][0-9]') # day digit 0-9
if (dayre.match(x)):
if (len(x) > size):
return tkMessageBox.showerror("Warning", "This "+ part +" is invalid")
app.destroy
else:
tkMessageBox.showinfo("OK", "Thanks for inserting a valid "+ part)
else:
tkMessageBox.showerror("Warning", part + " not entered correctly!")
root.destroy
#when clicked
chkDay(vDay.get(),31, "Day")
#interface of tkinter
vDay = StringVar()
Entry(root, textvariable=vDay).pack()
Problem:
Not validating, I can put in a day greater than 31 and it still shows: OK
root (application) does not close when I call root.destroy
Validating date with regex is hard. You can use some patterns from: http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5&AspxAutoDetectCookieSupport=1
or from http://answers.oreilly.com/topic/226-how-to-validate-traditional-date-formats-with-regular-expressions/
Remember that it is especially hard to check if year is leap, for example is date 2011-02-29 valid or not?
I think it is better to use specialized functions to parse and validate date. You can use strptime() from datetime module.
Let the standard datetime library handle your datetime data as well as parsing:
import datetime
try:
dt = datetime.datetime.strptime(date_string, '%Y-%m-%d')
except ValueError:
# insert error handling
else:
# date_string is ok, it represents the date stored in dt, now use it
31 is actually in your regex because [0-3][0-9] is not exactly what you're looking for.
You would better try to cast it to a int and explicitly check its bound.
Else the correct regex would be ([0-2]?\d|3[01]) to match a number from 0 up to 31
In order to limit the values between 1 and 31, you could use:
[1-9]|[12][0-9]|3[01]

Categories

Resources