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!
Related
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.
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()
I've been running into this problem with pyfolio where I just want to try out the example their github has here: https://quantopian.github.io/pyfolio/notebooks/bayesian/
the program runs through everything and takes awhile to calculate everything but in the end I get this
ValueError: Wrong number of items passed 4, placement implies 40
here is my current code:
import pandas_datareader as web
import pyfolio as pf
import datetime
start = datetime.datetime(2018, 10, 1)
end = datetime.datetime(2018, 12, 1)
stock_rets = web.DataReader("AAPL", 'yahoo',start , end)['Adj Close']
out_of_sample = stock_rets.index[-40]
pf.create_bayesian_tear_sheet(stock_rets, live_start_date=out_of_sample)
I even tried changing the out_of _sample value to less than 40 and then that sometimes would show an error of:
Bad initial energy, check any log probabilities that are inf or -inf,
nan or very small
any idea what might be causing this problem?
Workaround: Downgrade to PyMC3 v3.4.1
I tried running the tutorial that you indicated and also hit a similar error. Searching the GitHub repository, I saw someone reported a similar issue. Seems to be a problem with the recent versions of PyMC3 (3.5+). The suggested workaround is to downgrade to PyMC3 v3.4.1. Hopefully, someone eventually reworks the Pyfolio tutorial (the current version is from summer 2017).
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)
In Google Calendar, when you click on a date and enter an event, it just asks you to enter something into a text field and it'll automatically interpret what you entered.
So like, I'll enter dinner at 7PM, 7PM dinner, dinner 7PM, etc. the app would just understand what it is I'm typing.
How is this done?
Here's something in PHP: http://blog.builtbyprime.com/php/adding-google-quick-add-to-anything-the-textdate-php-class.
Realize this is an old post, but just in case this is useful for someone: here are some more options/ideas:
Option 1: Python
The dateutil library works quite nicely:
>> from dateutil.parser import parse
>> parse("tomrrow at 6pm", fuzzy=True)
Out[14]: datetime.datetime(2016, 11, 10, 18, 0)
>> parse("tomrrow at 6pm", fuzzy_with_tokens=True)
Out[15]: (datetime.datetime(2016, 11, 10, 18, 0), ('tomrrow at ',))
Option 2: Use the Google Calendar API
This is a bit of a hack, but it should work. You could use Google Calendar API's quickAdd:
Example request:
POST https://www.googleapis.com/calendar/v3/calendars/primary/events/quickAdd?text=Peter%2C+tomorrow+at+8am&key={YOUR_API_KEY}
Which would return an Event resource, You could use the data from this object for your needs.
Unfortunately, there doesn't seem to be a way to call quickAdd without actually creating an event in a calendar. So you'd kinda need to just have a throw-away Google calendar sitting in the background where the events would get created.