So this may be a very simple thing for most of you but I'm just starting out.
Below is my first ever class:
class WeatherYear:
DEFAULT_MAX = -99
DEFAULT_MIN = 999
DEFAULT_STR = 'DATE'
def __init__(self, year):
self.year = year
self.max_temp = WeatherYear.DEFAULT_MAX
self.min_temp = WeatherYear.DEFAULT_MIN
self.max_temp_date = WeatherYear.DEFAULT_STR
self.max_humid = WeatherYear.DEFAULT_MAX
self.min_humid = WeatherYear.DEFAULT_MIN
def add_day(self, date, max_temp, min_temp, max_humid, min_humid):
if max_temp and max_temp > self.max_temp:
self.max_temp = max_temp
self.max_temp_date = date
if min_temp and min_temp < self.min_temp:
self.min_temp = min_temp
if max_humid and max_humid > self.max_humid:
self.max_humid = max_humid
if min_humid and min_humid < self.min_humid:
self.min_humid = min_humid
And here is some stuff that I used it for:
years_dict = {}
wy_obj = years_dict.get(year)
if not wy_obj:
years_dict[year] = WeatherYear(year)
wy_obj = years_dict[year]
wy_obj.add_day(date, max_temp, min_temp, max_humid, min_humid)
This is part of my code, could someone please explain to me what is happening exactly, also the major part, Do i need to keep year in my __init__ function? What if I remove it? Would it still work the same way?
You should try out the code, that's the best way to understand OOP's concepts in Python.
Coming back to your question, according to your code, you need to have year in your init function else self.year = year would give an year not defined error
Question>: Do i need to keep year in my init function?
No, as you store a date in self.max_temp_date, thats doubled as you can get the year from date using self.max_temp_date.year.
Change your class WetherYear().__init__(... to the following:
def __init__(self, measure):
self.max_temp_date, self.max_temp, self.min_temp, self.max_humid, self.min_humid = measure
Thereby you don't have to initalize the class attributes with dummy values. Set the attributes at once with the first measure values.
About your naming of class methodes, name it to what this function are doing. In this case, you don't add anything you update the class attributs by condition.
def add_day(self, date, max_temp, min_temp, max_humid, min_humid):
if max_temp and max_temp > self.max_temp:
...
You don't have to get(... the WeatherYear object, to test if this year exists. use the key year only. Also you don't have to get it again wy_obj = years_dict[year], you can use it from the dict e.g. years_dict[year].add_day(...
wy_obj = years_dict.get(year)
if not wy_obj:
years_dict[year] = WeatherYear(year)
wy_obj = years_dict[year]
wy_obj.add_day(...
Consider this example:
from datetime import date
class WeatherYear:
def __init__(self, measure):
self.max_temp_date, self.max_temp, self.min_temp, self.max_humid, self.min_humid = measure
def update(self, measure):
if measure[1] > self.max_temp:
self.max_temp_date = measure[0]
self.max_temp = measure[1]
if measure[2] > self.min_temp:
self.min_temp = measure[2]
if measure[3] > self.max_humid:
self.max_humid = measure[3]
if measure[4] > self.min_humid:
self.min_humid = measure[4]
def __str__(self):
return "WeatherYear:In {year} at {self.max_temp_date}, measured a max temperature of {self.max_temp}°C and max humid of {self.max_humid} %".format(self=self, year=self.max_temp_date.year)
def main():
# date, max_temp, min_temp, max_humid, min_humid
measurements = [(date(2018, 9, 10), 20, 8, 40, 30),
(date(2018, 9, 12), 25, 12, 50, 35),
(date(2018, 9, 13), 19, 10, 30, 25)]
max_years = {}
for measure in measurements:
if not measure[0].year in max_years:
max_years[measure[0].year] = WeatherYear(measure)
else:
max_years[measure[0].year].update(measure)
for year in max_years:
print("{}: {}".format(year, max_years[year]))
if __name__ == "__main__":
main()
Output:
2018: WeatherYear:In 2018 at 2018-09-12, measured a max temperature of 25°C, max humid of 50 %
Tested with Python: 3.4.2
Related
I have seen other threads but couldnt figure it out based on that.
class DataConsolidationAlgorithm(QCAlgorithm):
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.SetStartDate(2017, 1, 1) #Set Start Date
self.SetEndDate(2020, 1, 1) #Set End Date
self.SetCash(100000) #Set Strategy Cash
self.SetBrokerageModel(BrokerageName.FxcmBrokerage)
symbols = [self.AddForex(ticker, Resolution.Minute).Symbol
for ticker in ["EURUSD"]]
self.SetBenchmark('SPY')
self.slow = self.EMA("EURUSD", 200, Resolution.Daily)
self.SetWarmUp(200)
def OnData(self, data):
# Simple buy and hold template
self.low = self.MIN("EURUSD", 7, Resolution.Daily, Field.Low)
self.high = self.MAX("EURUSD", 7, Resolution.Daily, Field.High)
#fxQuoteBars = data.QuoteBars
#QuoteBar = fxQuoteBars['EURUSD'].Close
#self.QuoteBar = self.History("EURUSD", TimeSpan.FromDays(1), Resolution.Daily)
self.quoteBar = data['EURUSD'] ## EURUSD QuoteBar
#self.Log(f"Mid-point open price: {quoteBar.Open}")
self.closeBar = (self.quoteBar.Close) ## EURUSD Bid Bar
self.history7days = self.History(["EURUSD"], 7, Resolution.Daily)
if self.closeBar <= self.low and self.Forex["EURUSD"].Price > self.slow.Current.Value:
self.SetHoldings("EURUSD", 1.0)
if self.closeBar > self.high:
self.SetHolding("EURUSD", 0.0)
Runtime Error: TypeError : Cannot get managed object
at OnData in main.py:line 50
:: if self.closeBar <= self.low and self.Forex["EURUSD"].Price > self.slow.Current.Value:
TypeError : Cannot get managed object
I was running into a similar error and solved it by making sure that the types of data I was trying to compare in the if statement with <, >, = etc were of the same type.
Redefine the indicators you want to compare as local indicators in OnData like below and all your indicators will be the same data type:
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.SetStartDate(2017, 1, 1) #Set Start Date
self.SetEndDate(2020, 1, 1) #Set End Date
self.SetCash(100000) #Set Strategy Cash
self.SetBrokerageModel(BrokerageName.FxcmBrokerage)
symbols = [self.AddForex(ticker, Resolution.Minute).Symbol
for ticker in ["EURUSD"]]
self.SetBenchmark('SPY')
self.slow = self.EMA("EURUSD", 200, Resolution.Daily)
self.SetWarmUp(200)
# Simple buy and hold template
self.low = self.MIN("EURUSD", 7, Resolution.Daily, Field.Low)
self.high = self.MAX("EURUSD", 7, Resolution.Daily, Field.High)
#fxQuoteBars = data.QuoteBars
#QuoteBar = fxQuoteBars['EURUSD'].Close
#self.QuoteBar = self.History("EURUSD", TimeSpan.FromDays(1), Resolution.Daily)
self.quoteBar = data['EURUSD'] ## EURUSD QuoteBar
#self.Log(f"Mid-point open price: {quoteBar.Open}")
self.closeBar = (self.quoteBar.Close) ## EURUSD Bid Bar
self.history7days = self.History(["EURUSD"], 7, Resolution.Daily)
def OnData(self, data):
closebar = self.closeBar.Current.Value
low = self.low.Current.Value
price = self.Forex["EURUSD"].Price
slow = self.slow.Current.Value
high = self.high.Current.Value
if closeBar <= low and price > slow :
self.SetHoldings("EURUSD", 1.0)
if closeBar > high:
self.SetHolding("EURUSD", 0.0)
kindly request function to get and calculates values in between time period with Python-Django function
the database example will be as below
Case(1) start_time = 01-11-2019 end_time = 15-12-2019 rate = 35.00
Case(2) start_time = 16-12-2019 end_time = 31-12-2019 rate = 50.00
i need function to calculate the rate as following:
user will request the period from 13-12-2019 till 18-12-2019
rate calculated [(13, 14, 15 December) = 35+35+35 = 105] + [(16, 17 , 18
December = 50+50+50 = 150] with total rate finally 255
class Items(models.Model):
name = models.CharField(max_length=200, db_index=True)
class Item(models.Model):
name = models.ForeignKey(Items, on_delete=models.CASCADE)
start_date = models.DateField()
end_date = models.DateField()
rate = models.DecimalField(max_digits=3, decimal_places=2)
I think this is what you're looking for. However, I'd be worried about multiple Item instances covering the same range of dates. If that's a real possibility, then the below function won't work properly.
request_lower = some_date
request_upper = some_other_date
items_within_range = Item.objects.filter(
Q(start_date__lte=request_lower, end_date__gt=request_lower)
| Q(start_date__lte=request_upper, end_date__gt=request_upper)
)
total = 0
for index in range((request_upper - request_lower).days):
# Iterate over the days from lower to upper.
date = request_lower + timedelta(days=index)
# Find the Item instance that the date is within the range.
total += [
i.rate for i in items_within_range
if i.start_date <= date < i.end_date
][0]
I'm calling a function to get the calculation for driver revenue but, I keep getting this error:
"line 396, in driver_get_revenue
monthly[month.strftime("%m")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
AttributeError: 'int' object has no attribute 'strftime'"
The function is this:
def driver_get_revenue(request):
driver = JWTAuthentication().authenticate(request)[0].driver
#Returns the difference between date and time.
from datetime import timedelta
revenue = {}
monthly = {}
yearly = {}
today = timezone.now()
month = today.month
year = today.year
#Created a range to calculate the current weekday.
current_weekdays = [today + timedelta(days = i) for i in range(0 - today.weekday(), 7 - today.weekday())]
for day in current_weekdays:
orders = Order.objects.filter(
driver = driver,
status = Order.DELIVERED,
created_at__year = day.year,
created_at__month = day.month,
created_at__day = day.day
)
revenue[day.strftime("%A")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
for day in range(0, 30):
orders = Order.objects.filter(
driver = driver,
status = Order.DELIVERED,
created_at__month = month,
created_at__day = day
)
(Line 396) monthly[month.strftime("%m")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
for month in range(0, 12):
orders = Order.objects.filter(
driver = driver,
status = Order.DELIVERED,
created_at__year = year,
created_at__month = month
)
yearly[year.strftime("%y")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
return JsonResponse({"revenue": revenue,
"month": monthly,
"yearly": yearly})
I'm not exactly sure where I went wrong. I marked line 396 so that you see where the error is. Any help will be greatly appreciated.
Thanks.
When you do this: month = today.month, month becomes an integer. The strftime function works with datetime objects, not with integers.
Therefore, month.strftime("%m") doesn't work.
Try day.strftime("%m") instead, or perhaps just month, depending on your requirements.
If instead you're looking for the month's name, you could do it like this:
today = timezone.now()
month = today.month
month_name = today.strftime("%B") # e.g. December
...
...and use the month_name variable in your code.
After solving a naive datetime problem I am facing a new problem on a view to generate graphs. Now I get mktime argument out of range.
I have no idea how to solve it. I didn't write the code, I am using it from a colleague of mine and I can't seem o understand why it fails. I think it has to do with a function that runs overtime and the error pops out.
#login_required(login_url='/accounts/login/')
def loggedin(request):
data = []
data2 = []
data3 = []
dicdata2 = {}
dicdata3 = {}
datainterior = []
today = timezone.localtime(timezone.now()+timedelta(hours=1)).date()
tomorrow = today + timedelta(1)
semana= today - timedelta(7)
today = today - timedelta(1)
semana_start = datetime.combine(today, time())
semana_start = timezone.make_aware(semana_start, timezone.utc)
today_start = datetime.combine(today, time())
today_start = timezone.make_aware(today_start, timezone.utc)
today_end = datetime.combine(tomorrow, time())
today_end = timezone.make_aware(today_end, timezone.utc)
for modulo in Repository.objects.values("des_especialidade").distinct():
dic = {}
mod = str(modulo['des_especialidade'])
dic["label"] = str(mod)
dic["value"] = Repository.objects.filter(des_especialidade__iexact=mod).count()
data.append(dic)
for modulo in Repository.objects.values("modulo").distinct():
dic = {}
mod = str(modulo['modulo'])
dic["label"] = str(mod)
dic["value"] = Repository.objects.filter(modulo__iexact=mod, dt_diag__gte=semana_start).count()
datainterior.append(dic)
# print mod, Repository.objects.filter(modulo__iexact=mod).count()
# data[mod] = Repository.objects.filter(modulo__iexact=mod).count()
dicdata2['values'] = datainterior
dicdata2['key'] = "Cumulative Return"
dicdata3['values'] = data
dicdata3['color'] = "#d67777"
dicdata3['key'] = "Diagnosticos Identificados"
data3.append(dicdata3)
data2.append(dicdata2)
#-------sunburst
databurst = []
dictburst = {}
dictburst['name'] = "CHP"
childrenmodulo = []
for modulo in Repository.objects.values("modulo").distinct():
childrenmodulodic = {}
mod = str(modulo['modulo'])
childrenmodulodic['name'] = mod
childrenesp = []
for especialidade in Repository.objects.filter(modulo__iexact=mod).values("des_especialidade").distinct():
childrenespdic = {}
esp = str(especialidade['des_especialidade'])
childrenespdic['name'] = esp
childrencode = []
for code in Repository.objects.filter(modulo__iexact=mod,des_especialidade__iexact=esp).values("cod_diagnosis").distinct():
childrencodedic = {}
codee= str(code['cod_diagnosis'])
childrencodedic['name'] = 'ICD9 - '+codee
childrencodedic['size'] = Repository.objects.filter(modulo__iexact=mod,des_especialidade__iexact=esp,cod_diagnosis__iexact=codee).count()
childrencode.append(childrencodedic)
childrenespdic['children'] = childrencode
#childrenespdic['size'] = Repository.objects.filter(des_especialidade__iexact=esp).count()
childrenesp.append(childrenespdic)
childrenmodulodic['children'] = childrenesp
childrenmodulo.append(childrenmodulodic)
dictburst['children'] = childrenmodulo
databurst.append(dictburst)
# print databurst
# --------stacked area chart
datastack = []
for modulo in Repository.objects.values("modulo").distinct():
datastackdic = {}
mod = str(modulo['modulo'])
datastackdic['key'] = mod
monthsarray = []
year = timezone.localtime(timezone.now()+timedelta(hours=1)).year
month = timezone.localtime(timezone.now()+timedelta(hours=1)).month
last = timezone.localtime(timezone.now()+timedelta(hours=1)) - relativedelta(years=1)
lastyear = int(last.year)
lastmonth = int(last.month)
#i = 1
while lastmonth <= int(month) or lastyear<int(year):
date = str(lastmonth) + '/' + str(lastyear)
if (lastmonth < 12):
datef = str(lastmonth + 1) + '/' + str(lastyear)
else:
lastmonth = 01
lastyear = int(lastyear)+1
datef = str(lastmonth)+'/'+ str(lastyear)
lastmonth = 0
datainicial = datetime.strptime(date, '%m/%Y')
datainicial = timezone.make_aware(datainicial, timezone.utc)
datafinal = datetime.strptime(datef, '%m/%Y')
datafinal = timezone.make_aware(datafinal, timezone.utc)
#print "lastmonth",lastmonth,"lastyear", lastyear
#print "datainicial:",datainicial,"datafinal: ",datafinal
filtro = Repository.objects.filter(modulo__iexact=mod)
count = filtro.filter(dt_diag__gte=datainicial, dt_diag__lt=datafinal).count()
conv = datetime.strptime(date, '%m/%Y')
ms = datetime_to_ms_str(conv)
monthsarray.append([ms, count])
#i += 1
lastmonth += 1
datastackdic['values'] = monthsarray
datastack.append(datastackdic)
#print datastack
if request.user.last_login is not None:
#print(request.user.last_login)
contador_novas = Repository.objects.filter(dt_diag__lte=today_end, dt_diag__gte=today_start).count()
return render_to_response('loggedin.html',
{'user': request.user.username, 'contador': contador_novas, 'data': data, 'data2': data2,
'data3': data3,
'databurst': databurst, 'datastack':datastack})
def datetime_to_ms_str(dt):
return str(1000 * mktime(dt.timetuple()))
I think the problem is with this condition.
while lastmonth <= int(month) or lastyear<int(year):
During December, month=12, so lastmonth <= int(month) will always be True. So the loop whill always return True, even once lastyear is more that the current year.
You want to loop if the loop is in the previous year, or if the loop is in the current year and the month is not in the future. Therefore, I think you want to change it to the following:
while lastyear < year or (lastyear == year and lastmonth <= month):
To be sure that the code is working and to understand it, you need to add lots of print statements to the loops, see how lastmonth and lastyear change, and check that the loop exits when you expect it to. You also need to test it for other values of year and month so that it doesn't break next month. Ideally you want to extract this bit of the code into a separate function. It would be easier to understand the loop if it only returned a list of (month, year) integers, instead of doing lots of date formatting at the same time. Then it would be easier to add unit tests.
I am reading data from a csv file, and there are date elements in it, but there is an inconsistency in the dates.
For example: sometimes the date element is like 1/1/2011 and sometimes it is like 01/01/2011
Since I am plotting this data later.. this causes a great deal of noise in my plots. The following is my date class. Can you help me out in where and how to modify the code in order to get the date in the form 01/01/2011
import re
class Date:
def __init__(self, input_date):
self._input_date = input_date
self._date = None
self._month = None
self._year = None
self._hour = None
self._min = None
def setDate(self):
date = self._input_date
#date = re.findall('w+',date)
date = self.__mySplit()
#print"len ",len(date)
assert (len(date) >= 3) #has atleast dd/mm/yy
#dateLength = len(date[0])
self._month = int(date[0])
self._date = int(date[1])
self._year = int(date[2])
if (len(date) ==5):
self._hour = int(date[3])
self._min = int(date[4])
def __mySplit(self): #splitting the date by delimiters..
res = [self._input_date]
#print res
seps = [' ','/',':']
for sep in seps:
s,res = res,[]
for seq in s:
res += seq.split(sep)
#print res
return res
Thanks
You definitely want to be using datetime. Here's some code that will get a datetime from either string type:
from datetime import datetime
def strToDatetime(dateStr):
return datetime.strptime(dateStr, "%d/%m/%Y")
Then, you can print a datetime out in the format you want with:
strToDatetime("1/3/2011").strftime("%d/%m/%Y)
>'01/03/2011'
You should never need to roll your own date/time/datetime structure in python.