Issue with datetime module - python

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()

Related

equal operator is not operating the way it should 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.

OS Time in Python 3.8.5

I've got the following dictionary in my code:
{
"morning": now.hour > 0,
"afternoon": now.hour > 12,
"evening": now.hour > 18,
"bit_late": now.hour > 21,
}
It's part of a Django project (v3.1), and whenever I run the server it throws up no errors, but it is using UTC time instead of my local system's time (+ 5 1/2 UTC). Hence, when I viewed the page at 3 PM, it wished me "Good morning" (which it's programmed to do). I've included the datetime library, but I don't know how to use it or any other library to try and get the program to run using system time.
Am I missing any particular library? What method should I use to get the system time, and where do I put it?
now = datetime.datetime.now()
This is the code I used for now, just for reference!
Thanks in advance!
Yep, I've got my answer. I simply used JavaScript to display the message instead of trying something with Django. Thanks to everyone!

Python TimeDelta Code works in Python IDE, but not when I run it through SPSS

I'm trying to calculate which fiscal week a day falls into, and my code runs correctly in Spyder and PythonTutor, but when I try running it through SPSS's Python functionality, I get a different error.
Code in Spyder:
from datetime import date, timedelta
VisitDate=date(2017,9,10)
def WhichWeek(DateOfVisit):
StartDate=date(2017,9,1)
EndDate=StartDate+timedelta(days=+6)
Beginning=StartDate
End=EndDate
NumberWeeks=10
for i in range(NumberWeeks):
if(DateOfVisit>=Beginning and DateOfVisit<=End:
print('It worked',i)
return i
else:
print ('It failed', i, Beginning, End)
Beginning=Beginning+timedelta(days=+7)
End=End+timedelta(days=+7)
WhichWeek(VisitDate)
This runs, and returns the expected value. (The print statements are there just to help troubleshoot it).
However, when I run it in SPSS using the Python Extension:
begin program.
def WhichWeek(DateOfVisit):
from datetime import date, timedelta
StartDate = date(2016,9,1)
EndDate=StartDate+timedelta(days=+6)
Beginning=StartDate
End=EndDate
NumberWeeks=10
for i in range(NumberWeeks):
if DateOfVisit>=Beginning and DateOfVisit<=End:
print('It worked',i)
return i
else:
print ('It failed', i, Beginning, End)
Beginning=Beginning+timedelta(days=+7)
End=End+timedelta(days=+7)
end Program.
SPSSINC TRANS RESULT=Week_Test /FORMULA WhichWeek(VisitDate).
EXECUTE.
FREQUENCIES VARIABLES=Week_Test
/FORMAT=DFREQ
/ORDER=ANALYSIS.
It now gives me the error "The Forumla References an undefined variable or could not be evaluated: can't compare datetime.date to float
VisitDate is a defined variable in my SPSS dataset, and since I don't get this error in Spyder, I'm at a loss for where to continue troubleshooting.
Edit: I changed my Spyder version from VisitDate1 to VisitDate to limit confusion. I should also say that in Spyder I'm running it against a static date to test if it identifies the week correctly (2017-09-10) and not an actual dataset. In SPSS, I'm running it against a dataset.

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)

Intermittent wrong date from time.strftime()

I have an Appengine app that still runs on the python2.5 runtime, which means it is single threaded. I have a school class:
class School(db.Model):
...
dateformat=db.StringProperty(default='%a %e %b',indexed=False) # For bookings
timeformat=db.StringProperty(default='%l:%M%P',indexed=False) # For bookings
def date(self,t):
return time.strftime(self.dateformat,time.gmtime(t))
def datetime(self,bt,et=None):
return time.strftime(self.dateformat+' '+self.timeformat,time.gmtime(bt))+\
(time.strftime(' - '+self.timeformat,time.gmtime(et)) if et else '')
def time(self,t):
return time.strftime(self.timeformat,time.gmtime(t))
Then when I want to format a date in the school's chosen format, I do this:
s=School.get_by_id(the_id)
date_string=s.date(the_timestamp)
Very occasionally, I get a date that is exactly a week out. So instead of "Wed 2 May" I get "Wed 9 May". This has been reported three times in the last week, out of probably tens of thousands of cases. All exactly a week out, none with any other time difference.
Nothing's changed in that part of my code for ages so I don't understand why this should suddenly start happening. Because it's single threaded, there shouldn't be issues with strftime, and I can't find any reports of thread issues with it anyway anyway.
Any ideas?

Categories

Resources