equal operator is not operating the way it should Python - python

I am currently trying to write an script which is checking if the current date and time is equal to a date and time in a file. But for some weird reason my main if statement is only being triggered when calling the > operator this means that the current date and time must be bigger than the date and time in the file to trigger the main if statement. But this is exactly what I want to avoid because at the end the script should be very precise and punctual. This operator causes also some bugs when starting my script because the function is working in a multiprocess with other functions. When callig the == operator instead of the > operator the if statement is not being triggered. I wonder if my program is formatting a parameter wrong and this might cause the none equality problem.
This is my code:
#the content of the safe_timer.txt file is for example 05.11.2021 01:05:10
#the current time is for example 05.11.2021 01:05:00.
#The while loop should theoretically loop until ga is equal to alarm_time
#but when calling if ga==alarm_time: nothing is happening at all.
#Am I doing something wrong while formatting the two parameters?
#Or why is nothing happening when calling if ga==alarm_time:?
#ga = current time
#alarm_time = file content
#both parameters should be formated to the same format when running the script
import time
import datetime
from datetime import datetime
def background_checker():
with open('safe_timer.txt','r+') as sf_timer:
while True:
try:
formatit = '%d.%m.%Y %H:%M:%S'
if len(str(sf_timer)) > int(0):
ga = datetime.now()
for lines in sf_timer:
alarm_time = datetime.strptime(lines, formatit)
ga = datetime.strptime(ga, formatit)
if ga == alarm_time: #That's the point where I am not sure what I've made wrong because ga should equal at some time alarm_time and everything should be fine. Remember that > is not a solution because this function is operating in a multiprocess and this operator is causing bugs when starting the script
print('alarm')
except Exception as err:
continue
Is there something I am doing wrong? If so I would be very glad if someone could explain to me what I've made wrong and help me solve this problem:)
Thank's for every help and suggestion in advance:)
PS: Feel free to ask questions:)

It seems like the comparison never happens because an exception occurs before that:
>>> ga = datetime.now()
>>> formatit = '%d.%m.%Y %H:%M:%S'
>>> datetime.strptime(ga, formatit)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: strptime() argument 1 must be str, not datetime.datetime
However, you swallow up all exceptions so you probably didn't see that. strptime converts strings to datetime objects. You should decide whether to compare strings (in which case, format ga properly) or datetimes (in which case, call strptime on the string data in your file.

Related

Issue with datetime module

I'm trying to make a simple Python function that prints
two things;
What day of the week it currently is.
How many days it is until Christmas.
I don't get any errors when I run this, however nothing prints either.
In fact nothing at all happens when its run.
I've checked and I've installed the datetime module correctly (I think).
I'm not really sure what I'm doing wrong so any guidance would be helpful.
As you can probably guess, I'm relatively new to Python/stackoverflow.
Thanks.
Edit: I stupidly named the file itself datetime.py because yes I am that stupid.
from datetime import *
def day_of_week():
""" Python function to return a specified day of the week"""
today_date = date.today()
thisYear = today_date.year
xmas = date(thisYear,12,25)
day_of_week =("Mon","Tue","Wed","Thu","Fri","Sat","Sun")[today.weekday]
print("It's a %s." % (day_of_week))
days_to_xmas = (xmas - today_date).days
print("There are %i days to xmas!" & days_to_xmas)
Try calling the function in the script , you defined the function but never executed it.
day_of_week()

Code resulting in weird datetime result on Google App Engine

I'm running a python program on Google App Engine that uses the datetime function. It's supposed to always return UTC time, but it seems to intermittently give an incorrect time. I'm not sure if there's an error with my code, or whether this is an issue on Google's side.
To get my local time (GMT +8:00), I run this function:
def SGTOffset(obj=datetime.now()):
if isinstance(obj, datetime):
return obj + timedelta(hours=8)
return SGTOffset(datetime.now())
and in my main program:
today_date = commoncode.SGTOffset().date()
logging.debug('Today date: %s | Today datetime: %s' % (today_date.isoformat(), commoncode.SGTOffset().isoformat()))
In the logs, I get the following:
[25/Nov/2015:09:00:02 -0800] "GET ... etc ...
01:00:03.287 Today date: 2015-11-25 | Today datetime: 2015-11-25T15:38:20.804300
So, Google kindly formats the log datetime to my locale (GMT +8), showing that the code is run at 01:00:03.287 (26th Nov, GMT +8). Also, this is confirmed by the timestamp 25/Nov/2015:09:00:02 -0800 provided. So the code was run at 25/Nov/2015 17:00:02 UTC time.
However, my code is outputting the wrong time. The datetime that is being generated in the code 2015-11-25T15:38:20.804300 has the timezone of GMT-9:30 instead of UTC time. (Because SGToffset() adds 8 hours to datetime)
This is quite catastrophic as I use the local datetime in many areas of my program. This is also happening intermittently only, because yesterday, the same code ran and got this log:
[24/Nov/2015:09:00:00 -0800] "GET ... etc ...
01:00:02.237 Today date: 2015-11-25 | Today datetime: 2015-11-25T01:00:01.768140
Which is correct! (Google's log timestamp 01:00:02.237 matches the time generated by SGTOffset() which is 01:00:01)
Could I know what is wrong with my program, or whether this is an issue with Google App Engine?
Thank you spending time to read this question!
The problem lies with the code.
Python stores a default value of the parameter obj for the function SGTOffset() when it is first defined (when the function object is first instantiated), instead of whenever the function is called as I intuitively expected. So, the datetime value will reflect the start time of the instance in GAE.
In order to get the current time whenever I call SGTOffset() without any parameters, I should instead have used:
def SGTOffset(obj=None): # Instead of obj=datetime.now() which is converted to obj='specific datetime' when instantiated
if isinstance(obj, datetime):
return obj + timedelta(hours=8)
return SGTOffset(datetime.now())
In this case, datetime.now() is called dynamically whenever it is required.
I arrived at this solution after viewing a question about old datetime values being returned.
I'm adding a quick answer to give you suggestions to make your code more readable:
obj is not a good variable name because it is not informative
No need for a recursive call to the function
Better to not use isinstance because is None gives you the needed functionality and your code will not work if some other instance type is given anyway.
Here is my suggestion:
def SGTOffset(dt=None):
if dt is None:
dt = datetime.now()
return dt + timedelta(hours=8)
Or if you prefer brevity:
def SGTOffset(dt=None):
return (dt or datetime.now()) + timedelta(hours=8)

Python: 'float' object is not subscriptable when iteration function

I am teaching myself Python and am trying out a challenge I found to create a quote program for a gardener. I have almost all of it working and have added in iteration so that the user can make more than one quote without re-starting the program.
It produces the quote perfectly the first time but on the second run it presents this error:
Traceback (most recent call last):
File "/Users/shaunrogers/Desktop/Plymstock Prep/GCSE CS/SOL/Controlled Assessment/Sample Papers Solutions/gardening Task 2.py", line 105, in <module>
lawn = m2_items("lawn",0)
File "/Users/shaunrogers/Desktop/Plymstock Prep/GCSE CS/SOL/Controlled Assessment/Sample Papers Solutions/gardening Task 2.py", line 23, in m2_items
minutes = area*time[index]
TypeError: 'float' object is not subscriptable
I have the following code as a function that is producing the error:
def m2_items (item,index):
global costs, time, LABOUR
length = int(input("How long is the "+ item+"?\n"))
width = int(input("How wide is the "+item+"?\n"))
area = length*width
cost_m2 = float(costs[index])
total_cost = area*cost_m2
minutes = area*time[index]
hours = int(minutes/60)
labour = LABOUR*hours
labour_cost=round(labour,2)
m2_details = [area, cost_m2, total_cost,hours, labour_cost]
return m2_details
I have tried re-setting the local variables on the running of the function (but I didn't think this was needed as the variables should be removed from memory once the function has run).
I hope the question is clear and that I can get some insight. To re-iterate, what I want the program to do is allow me to call this function multiple times.
You are using the global time variable, which is initially subscriptable (probably an array). As your program continues, some other part of your code will assign a new value to time, maybe accidentally because you wrote time = some_calculation() instead of time[i] = some_calculation(), or maybe you are using the name time somewhere else without realizing it's already in use.
Do a search for all the places where you use the name time and you will probably find your error.
This is a common problem with global variables. Sometimes something updates them from another part of the code, and the error will sneak up on you like this.

Not allowing numbers in Glade with Python

I'm a fairly new Python programmer (started 3 days ago). I'm working as a apprentice for a civil engineer and he asked me to do some simpler tasks for his program, as of the objective I should work with is to not allow numbers from inputs in certain glade objects.
The code I've been struggling with creating is as such:
def testOmHeltal (self, number1):
textviewResultat = self.builder.get_object("textviewResultat")
text = gtk.TextBuffer()
try:
#print number1.get_text()
#temp = number1.get_text() + number1.get_text()
temp = float(number1.get_text())
except ValueError:
text.set_text("ERROR: Endast Nummer")
self.builder.get_object("hboxWarning").show()
self.builder.get_object("image12").show()
self.builder.get_object("textviewResultat").set_buffer(text)
return 0
self.builder.get_object("hboxWarning").hide()
self.builder.get_object("image12").hide()
def quit(self, widget):
sys.exit(0)
This code is called upon at the location of the glade object with this line:
self.testOmHeltal(entryGladeObject)
Now to the problem at hand, I allways get an Float error as such:
File "bvf.py", line 393, in utfora
+float(entryTjockleksskyddslager.get_text<>>>>
ValueError: invalid literal for float<>: 0.04e
0.04e is the invalid input and line 393 is a piece of my Chiefs code, since all he uses is float all the time and I shouldn't meddle with it too much I'm kind of panicking alittle..
I understand that float can only start and end with a number to not give an error, but since my "code" bit wants an error(or rather, an exception) to start the 'hboxWarning' and 'image12' of someone using a letter instead of the supposed number, I'm at a loss at what to do ><
Instead of showing my error with hboxWarning and image12, nothing happens at all...
Any hints or advice would help alot.
I don't know if I understood correctly, but the error is not on your code, right?
All I can assume is that there's a piece of code trying to convert the value to float before your verification. If that's the case, you should verify the value before any processing is done on it, or move the try-except code around the faulty code, depending on the processing itself (for example, if the processing implies database manipulation, it would be safer to do all the verifications previously).
If the error is happening before the line where you run self.testOmHeltal(entryGladeObject), the execution of the signal/method stops right away and your code is never excecuted; that's why the warning isn't showing.

Select module claiming that at most 3 arguments can be accepted (no optional timeout)

I'm attempting to write a program that waits for readline input, but only for a limited span of time for non-blocking input. From another question on stackoverflow, I was alerted to the Select module. It seemed to fit the bill for me. However, when I attempt to implement it, as follows:
i,o,e = select([sys.stdin],[],[],5)
as described in docs.python.org, (I'm only interested in input, and in this example, a timeout of 5 seconds) I get an error message reading:
TypeError: select() takes at most 3 arguments (4 given)
If I instead call it as:
i,o,e = select([sys.stdin],[],[])
Then I get:
ValueError: list of cases must be same length as list of conditions
with a calling module of /usr/lib/pymodules/python2.7/numpy/lib/function_base.py line 718.
I'm running ubuntu 11.10, with Python 2.7.2+.
Can anyone shed some light on this for me? I really need the timeout functionality.
Sounds like you're calling the numpy.select function , but you want the select.select function. Import them accordingly.

Categories

Resources