Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am new in Django.
I created Sponsor model that model has start_date (start date become sponsor) and end_date (end date of sponsor).
start_date = models.DateField(
_("Start date"),
default=datetime.date.today)
end_date = models.DateField(
_("End date"),
default=datetime.date.today)
I want to put all logic inside the model, if that not possible then I want to put the logic in a view. I make method current_sponsor which can return True or False (if today is on a range of start_date and end_date means True else False).
This is my current_sponsor method
def current_sponsor(self):
today = datetime.date.today
if today >= self.start_date:
return True
elif today <= self.end_date:
return True
else:
return False
The problem is I got error can't compare datetime.datetime to builtin_function_or_method.
I've tried to see the data using django shell it seem works but the reality does not work.
datetime.date.today is not calling the function you think it is:
>>> import datetime
>>> datetime.date.today
<built-in method today of type object at 0x7fb681a90f80> # NOT CALLING FUNCTION
>>> datetime.date.today() # You need () at the end
datetime.date(2015, 11, 4)
If you add the parentheses, you'll get the result you expect.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
import datetime
from datetime import date
def get_one_week():
global date
seven_dates = []
date = date.today()
for i in range(7):
date += datetime.timedelta(days=-1)
date_str = date.strftime('%Y%m%d')
seven_dates.append(date_str)
return seven_dates
print(get_one_week())
This will print out:
['20220901', '20220831', '20220830', '20220829', '20220828', '20220827', '20220826']
My question, both 'date' and 'datetime' are imported variables, but why do I have use a global declaration for the 'date' but not for the 'datetime' variable?
It's because you declared your variable date so python thinks that you referenced the local variable before any assignment try change it to other name so it will use the global one
import datetime
from datetime import date
def get_one_week():
seven_dates = []
d = date.today()
for i in range(7):
d += datetime.timedelta(days=-1)
date_str = d.strftime('%Y%m%d')
seven_dates.append(date_str)
return seven_dates
print(get_one_week())
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm relatively new to python so I think this may be an easy question, but it has me confused. Here is my code:
# Mike Fitzgibbon CS4250 Project4 implement class diagram
# define the class
class Product:
# name is the name of the product
name = None
# price is how much the product costs
price = None
# discount percent is how much the discount is in percentages
discountPercent = None
# define the constructor
def __init__(self, n, p, d):
# initialize variables
self.name = n
self.price = p
self.discountPercent = d
# define get discount by returning the discount
def getDiscountAmount(self):
return self.discountPercent
# define discount price by returning the discount percent times the price
def getDiscountPrice(self):
return self.discountPercent*self.price
# define get description by creating description using field variables
def getDescription(self):
print("Name: "+self.name)
print("Price: "+self.price)
print("Discount: "+self.discountPercent+"%")
print("Discount price: "+self.getDiscountPrice())
def __main__():
p=Product("A",100,90.0)
print(p.getDescription())
Nothing prints out when I run this code. Why? How do I fix this?
To run your __main__() function, you can add to the end of your program:
if __name__ == "__main__":
__main__()
For printing the values, change print(p.getDescription()) to p.getDescription() because calling the function in class will output the values. BTW, you cannot concatenate int/float with str, so you should convert int/float to string, like print("Price: "+str(self.price))
you would need to add;
if name == '__main__':
main()
the reason for this is that you have defined the function main, but have not told the computer to run it.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I need a function returning a boolean indicating if midnight has just passed.
I came up with this but I am not happy with the "form". Can anyone think of anything better? as in terms of efficiency/elegance?
from datetime import datetime, timedelta
def passed_midnight(delta=1):
time_now = datetime.today # see other comment below
time_ago = time_now() - timedelta(minutes=delta)
# next line with a dummy delta (zero) cuz "datetime.today - timedelta(days=1)" gives an error
today = time_now() - timedelta(days=0)
return today.strftime("%Y%m%d") != time_ago.strftime("%Y%m%d")
>>> print(passed_midnight, 10)
datetime.today - timedelta(days=1) gives an error because datetime.today is a function that needs to be called. This is why you must have felt the need to write time_now() with parentheses: it's calling the function, twice (with different results, because time has a tendency to pass).
Avoid strftime in favour of date(), which returns the date part only (as a datetime.date object).
Use datetime.now() instead of datetime.today() so that subtracting a timedelta can take the timezone (and hence daylight savings time changeovers) into account.
So then you get this:
from datetime import datetime, timedelta
def passed_midnight(delta=1):
time_now = datetime.now()
time_ago = time_now - timedelta(minutes=delta)
return time_now.date() != time_ago.date()
You probably misunderstood how to declare a function and how to call it.
Here is a version that fixed the issues with function calls:
from datetime import datetime, timedelta
def passed_midnight(delta=1):
today = datetime.today()
time_ago = today - timedelta(minutes=delta)
return today.strftime("%Y%m%d") != time_ago.strftime("%Y%m%d")
>>> print(passed_midnight(10))
False
Be careful, this code doesn't take care of time zones. The behavior will be different from a location to another
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What would a piece of code look like which checks today's date, and if it's a particular date, it will print out a message?
The context is that I'm making a birthday cake for my son who codes and I want to write a themed Happy Birthday message on top correctly. (Sorry, not as clever or serious as a lot of the things on here!)
I'd like something which is basically:
johnsBirthday = 01/01/1998
johnsAge = todaysdate - johnsBirthday (in years)
if todays date == 01/01/XXXX then print("Happy Birthday John!" + johnsAge + " today!")
My knowledge of python is very limited (as I'm sure you can tell from the above) but I vaguely know how to do this in Excel, so I figure there must be a way to do it in python too?
I know could always just write out:
print("Happy Birthday, John!")
and he'd appreciate that, but I think it would really make him smile to go a little further than that!
# Import datetime class from datetime module
from datetime import datetime
birthday = "20/09/1998"
# Parses the string into a datetime object
birthday_obj = datetime.strptime(birthday, '%d/%m/%Y')
# Gets todays date
now = datetime.now()
# Checks the day and month to verify birthday status
if(birthday_obj.day == now.day and birthday_obj.month == now.month):
johns_age = str(now.year - birthday_obj.year)
print("Happy Birthday John! " + johns_age + " today!")
For your purpose, it might be easier to use regular expressions if you are familiar with them. You can search any patterns you like, after converting datetimes to string, or better yet if you already have datetimes in string formats.
For datetime to string format conversion codes, check out -
format-codes
Example code
import re
from datetime import datetime
pattern = re.compile(r'^01/01/')
today_date = datetime.now().strftime(r'%d/%m/%Y')
some_date = '01/01/2021'
print(re.match(pattern, some_date)) # <re.Match object; span=(0, 6), match='01/01/'>
print(today_date) # 20/09/2020
print(pattern.match(today_date)) # None
Edit - Had forgotten that age needs to be calculated!
import re
from datetime import datetime
johns_birthday = '01/01/1998'
if (re.match('^01/01/', johns_birthday)):
johns_age = datetime.now().year - datetime.strptime(johns_birthday, r'%d/%m/%Y').year
print("Happy Birthday John! " + str(johns_age) + " today!")
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
def DS():
import os
import pandas as pd
directory=input('What folder would you like to work in? ( Example: /Users/hem/Desktop/pythontest/ ')
filename=input('Please enter the name (including .csv) of the file you would like to analyze ' )
idkey=input('What is the subject ID you are analyzing? ' )
sessionkey=input('What session of testing are you analyzing? ')
print('---------- Calculating Drug Stroop endpoints ----------')
os.chdir(directory)
dataframe = pd.read_csv(filename, error_bad_lines=False)
output={}
CategoryID = dataframe['CategoryID'].tolist
ReactionTime = dataframe['ReactionTime'].tolist
CorrectResponse = dataframe['CorrectResponse'].tolist
#Stroop interference score
totalN = 0
countN = 0
CorrectResponseNeutral = 0
for i in range(len(CategoryID)):
if CategoryID[i] == 1:
totalN + ReactionTime[i]
countN + 1
CorrectResponseNeutral + CorrectResponse[i]
AverageRTNeutral = totalN/countN
CorrectResponseNeutral = CorrectResponseNeutral/countN
totalD = 0
countD = 0
CorrectResponseDrug = 0
for i in range(len(CategoryID)):
if CategoryID[i] == 2:
totalD + ReactionTime[i]
countD + 1
CorrectResponseDrug + CorrectResponse[i]
AverageRTDrug = totalD/countD
CorrectResponseDrug = CorrectResponseDrug/countD
InterferenceScore = AverageRTNeutral - AverageRTDrug
output['SubjectID'] = idkey
output['Session'] = sessionkey
output['Interference Score'] = InterferenceScore
output['Accuracy of Neutral Trials'] = CorrectResponseNeutral
output['Accuracy of Drug Trials'] = CorrectResponseDrug
print('---------- Done calculating endpoints ----------')
outputname=input('What would you like to name your outputfile? (Please include.csv)')
outputdataframe = pd.DataFrame.from_dict([output])
outputdataframe.to_csv(os.path.join('/Users/hem/Desktop/Analysis/DrugStroopAnalyzed',outputname))
Hey Guys. Im trying to write a script that would calculate endpoints for a medical task. When I run the program, it works all the way until it hits the first for loop of the script. I'm pretty sure there is an error because CategoryID doesnt have a length property. But I also think it should because I'm converting it to a list in the beginning. Any suggestions on how to fix this? Thanks in advance.
It seems like you forgot the () after tolist method, so it can be parsed as a call to the method, and not the method itself:
CategoryID = dataframe['CategoryID'].tolist()
ReactionTime = dataframe['ReactionTime'].tolist()
CorrectResponse = dataframe['CorrectResponse'].tolist()