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'>
Related
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
import datetime
now = datetime.datetime.now()
if now.day == Tuesday :
print ('yes it is tuesday')
else :
print ('no')
I try this but I get error in python :
Traceback (most recent call last):
File "C:/Users/Yarlagadda/Desktop/test2.py", line 4, in <module>
if now.day == Tuesday :
NameError: name 'Tuesday' is not defined
>>>
I would like to know mistake
You have two problems with your code.
The first is that the error code is telling you that Tuesday doesn't exist as a variable because you are not making it a string. So change it to 'Tuesday' with the ' around it.
Second is that now.day is going to return a number and not a string day.
Edit: Thanks to #Tomerikoo for pointing out that this returns the day of the month and not the day of the week. Change this to now.weekday() to get the day of the week.
To fix this, you can either compare the number 1 in the if statement instead of the word Tuesday or you can map the numbers to the words. Mapping the numbers to the words is the preferred method since it is easier to maintain and less messy.
Note: The days of the week in now.weekday() will be numbered 0-6 with 0 being Monday and 6 being Sunday.
I'm using a tuple here, but you could use a list, or if you really feel inclined, a dictionary. But a dict is overkill and a list comes with memory overhead that's not needed.
Mapping:
week_days = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
Final Code
import datetime
week_days = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
now = datetime.datetime.now()
day = week_days[now.weekday()] # Note the change to now.weekday()
if day == 'Tuesday' :
print ('yes it is tuesday')
else :
print ('no')
The error is just in if condition that the Tuesday is not used as string. Replace Tuesday by 'Tuesday' and your code is working fine.
For enhancement you may also use list or tuple to keep the weekdays.
import datetime
now = datetime.datetime.now()
if now.day == 'Tuesday':
print ('yes it is tuesday')
else:
print ('no')
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()
Everything up here is fine
from datetime import datetime
while True:
now = str(datetime.now())
decisecond = now[20]
This part doesn't work
if decisecond == 1:
print(time)
It's because 'decisecond' isn't an int. Change the if statement to this, and it will work:
if int(decisecond) == 1:
print(time)
In saying that, printing 'time' will not print what I think you want it to. Probably change it to print the datetime, so the whole code is:
from datetime import datetime
while True:
now = str(datetime.now())
decisecond = now[20]
if int(decisecond) == 1:
print(datetime.now())
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]