question about counting time calculated by property - python

I have created a date and time delta property. this property calculates the total time between two date and times for a job. Now I want to create a property that sums all the time of the jobs and represents it on a card. I have tried many ,but no success. Hopefully someone has a solution
#property
def Get_time_diference(self):
start_time = self.date
end_time = self.dateTo
total = end_time - start_time
return total

Try making "total" an attribute of the class
class TimeClass:
def __init__(self):
self.total =0
#property
def Get_time_diference(self):
start_time = self.date
end_time = self.dateTo
diff = end_time - start_time
self.total+=diff
return diff
def get_total(self):
return self.total
Another solution could be using global
global total
total=0
#property
def Get_time_diference(self):
start_time = self.date
end_time = self.dateTo
diff = end_time - start_time
total+=diff
return diff

Related

Printing entries in a dictionary in descending order

Printing entries in a dictionary in descending order so that I can view them according to the example
08:02 - registration
08:45 - doctor checkup
09:00 - procedure
09:15 - doctor checkup
09:25 - radiography
10:30 - blood test
11:00 - doctor checkup
11:30 - hospital discharge
class Time():
def __init__(self, hour, minutes):
self.hour = hour
self.minutes = minutes
def __str__(self):
return "%02d:%02d" % (self.hour, self.minutes)
def __repr__(self):
if self.minutes == 0:
return 'Time({0},{1}0)'.format(self.hour, self.minutes)
return 'Time({0},{1})'.format(self.hour, self.minutes)
class Event():
def __init__(self, time, nameStattion):
self.time = time
self.nameStattion = nameStattion
def __str__(self):
return "{0}-{1}".format(self.time, self.nameStattion)
def __repr__(self):
return 'Event(Time(%d,%d),"%s")' % (self.time.hour, self.time.minutes, self.nameStattion)
class MedicalRecord():
data = {}
def __init__(self, name, id):
self.name = name
self.id = id
def __repr__(self):
return 'Event(Time(%d,%d),"%s")' % (self.time.hour, self.time.minutes, self.nameStattion)
def add(self, time, station):
self.data[time] = Event(Time(int(time[0:2]), int(time[3:5])), station)
def view(self):
#for i in range(len(self.data)):
print(eval(repr(self.data)))
time1 = Time(8, 2)
time1
print(time1)
time2 = eval(repr(time1))
print(time2)
event1 = Event(time1, 'registration')
event1
event2 = eval(repr(event1))
print(event2)
record1 = MedicalRecord('David', 1)
record1.add('08:02', 'registration')
print(record1.data)
record1.add('09:15','doctor checkup')
record1.add('08:45','doctor checkup')
record1.add('09:00','procedure')
record1.add('11:00','doctor checkup')
record1.add('09:25','radiography')
record1.add('11:30','hospital discharge')
record1.add('10:30','blood test')
record1.view()
In my example it prints as one side list
You would want to use the python sorted() function. It will have a key argument which you can pass a function that returns the time and python will sort the list according to that. From there you will probably get an ascending list which you can just do list.reverse() to make it descending.
Edit: actully sorted lets you choose if its acending or decending using the "reverse" argument. See the sorted link for more info.
def keyFunc(EventObj): return f'{EventObj.time}'
sortedList = sorted(SomeEventList, key=keyFunc, reversed = True)
def view(self):
for key in sorted(self.data):
print(key, '-', self.data[key])

OOP - Creation of Class, iterating through an album of songs?

I'm learning about OOP and I need some help with defining one of the methods under Album, specifically total_runtime.
Here's some code (verified, all correct) on the context of the question.
class Duration(object):
def __init__(self, minutes, seconds):
self.total_seconds = minutes * 60 + seconds
self.minutes = int(self.total_seconds / 60)
self.seconds = self.total_seconds % 60
def get_minutes(self):
return self.minutes
def get_seconds(self):
return self.seconds
def __str__(self):
# returns the string representation of the Duration in "mm:ss" form.
if len(str(self.minutes)) < 2:
self.minutes = "0" + str(self.minutes)
if len(str(self.seconds)) < 2:
self.seconds = "0" + str(self.seconds)
return str(self.minutes) + ":" + str(self.seconds)
def __add__(self, duration):
#Adds 2 durations together
return Duration(self.minutes + duration.minutes, self.seconds + duration.seconds)
class Song(object):
def __init__(self, artist, title, duration):
self.artist = artist
self.title = title
self.duration = duration
def get_artist(self):
return self.artist
def get_title(self):
return self.title
def get_duration(self):
return self.duration
class Album(object):
def __init__(self, artist, title):
self.artist = artist
self.title = title
self.songs = list()
def add_song(self, song):
# Adds song (of class Song) to the album.
self.songs.append(song)
I need some help with defining the property total_runtime(self) under class Album which is supposed to return the total runtime (of class Duration) of the album.
Here's what I have now. I tried iterating through the album to get the durations of all the songs. Somehow I'm getting an error which says that add is not defined.
def total_runtime(self):
duration = (0,0)
for song in self.songs:
__add__(self, duration)
return duration
Would really appreciate any help debugging! Thank you!
You need to call __add__ as an attribute of the class, the self argument is the object you're calling from. It's implicitly moved into the arguments.
def total_runtime(self):
duration = Duration(0,0)
for song in self.songs:
duration.__add__(song.get_duration())
return duration
But really, __add__ is more cleanly used with the plus operator:
def total_runtime(self):
duration = Duration(0,0)
for song in self.songs:
duration += song.get_duration()
return duration

python calculate time problem in function

I'm trying to create a Parking Lot in OOP.
I got stuck in payment calculated.
The payment is only calculated in seconds, how can I make it hourly or part of it?
(Under function “VehicleLeaves” I calculated secondsDiff.seconds because if I change it to secondsDiff.hour the program will crash.)
My Code:
import datetime
class Cars:
def __init__(self, phone, car_type, plate):
self.__phone = phone
self.__car_type = car_type
self.__plate = plate
def __str__(self):
return f"Plate: {self.__plate}, Phone: {self.__phone}, Car Type: {self.__car_type}."
class ParkingLot:
def __init__(self, name, capacity=1):
''' return a ParkingLot object with name "name" '''
self.name = name
self.capacity = capacity
self.earnings = 0
self.rate = 15
self.carsAndEnterTime = {}
def SetCapacity(self, newCap):
''' change the capacity from the default 1 '''
if newCap < 1:
raise RuntimeError("Error: parking lot size cannot be less than 1")
self.capacity = newCap
def GetCapacity(self):
''' return parking lot capacity '''
return self.capacity
def GetEarnings(self):
''' return how much much parking has made '''
return self.earnings
def VehicleEnters(self, vehicle):
''' vehicle enters parking lot'''
# put car and its enter time in a dictionary
self.carsAndEnterTime[vehicle] = datetime.datetime.now()
if self.capacity == 0:
raise RuntimeError("Error: Parking lot full!")
self.capacity -= 1
def VehicleLeaves(self, vehicle):
''' vehicle leaves parking lot. when it leaves, charges money '''
secondsDiff = datetime.datetime.now() - self.carsAndEnterTime[vehicle]
self.earnings += self.rate * secondsDiff.seconds
# after earned money, delete vehicle from dictionary
del self.carsAndEnterTime[vehicle]
self.capacity += 1
def __str__(self):
''' prints basic information of parking lot '''
return f"Parking lot: {self.name} \nSpots open: {self.capacity} \nHourly rate:{self.rate}\n {self.carsAndEnterTime}\nEarnings: $ {self.earnings} "
Focus on the area in the code of time calculation:
def VehicleEnters(self, vehicle):
''' vehicle enters parking lot'''
# put car and its enter time in a dictionary
self.carsAndEnterTime[vehicle] = datetime.datetime.now()
def VehicleLeaves(self, vehicle):
''' vehicle leaves parking lot. when it leaves, charges money '''
secondsDiff = datetime.datetime.now() - self.carsAndEnterTime[vehicle]
self.earnings += self.rate * secondsDiff.seconds
# after earned money, delete vehicle from dictionary
del self.carsAndEnterTime[vehicle]
self.capacity += 1
result in seconds, for this example is 10 seconds:
Earnings: $ 150
How can I calculate instead of seconds in hours or part of an hour rate of 15$.
For example, an hour and a half equals to 30$
what i did worng?
You can do a roundup withceil of math module:
import math
secondsDiff = datetime.datetime.now() - self.carsAndEnterTime[vehicle]
hour_roundup = math.ceil(secondsDiff.seconds/3600)

Returning a dictionary with all dates between a start and an end date

I have a Calendar on one of my django views. I am trying to return a dictionary with a list of dates between a start and an end date.
At the moment, I can only return a list of start dates or end dates. I need these along with all the days in between to be part of the dictionary.
class HolidayCalendar(HTMLCalendar):
def __init__(self, holiday):
super(HolidayCalendar, self).__init__()
self.holiday = self.holiday_days(holiday)
#some formatting
def holiday_days(self, holiday):
#don't actually know how this works....
field = lambda holiday: holiday.start_date.day
# field = lambda holiday: holiday.end_date.day
return dict(
[(day, list(items)) for day, items in groupby(holiday, field)]
)
In all honesty, I don't fully understand this at all...
This is the view that calls this:
def holiday(request):
#some code
date_today = datetime.now()
year = date_today.year
month = date_today.month
my_holidays = Holiday.objects.order_by('start_date').filter(
Q(start_date__year=year, start_date__month=month) | Q(end_date__year=year, end_date__month=month)
)
cal = HolidayCalendar(my_holidays).formatmonth(year, month)
#form stuff
context = {
"holidayform": holidayform,
"calendar": mark_safe(cal),
}
return render(request, "tande/calendar.html", context)
Thanks!
Having start and end dates you can just add a timedelta of 1 day to the former until you reach the latter. Something like this:
day_delta = timedelta(1,0,0)
next = start_date
days = []
while (end_date - next) < day_delta:
next = next + day
days.append(next)
So now days will have a list of all the days between start_date and end_date
Here is my solution, I didn't need a dictionary in the end I just used a list:
class HolidayCalendar(HTMLCalendar):
def __init__(self, holiday):
super(HolidayCalendar, self).__init__()
self.holiday = self.holiday_days(holiday)
def holiday_days(self, holiday):
day_delta = timedelta(1,0,0)
holidays = Holiday.objects.all()
days = []
for balloon in holidays:
next = balloon.start_date
end = balloon.end_date
while (end - next) > day_delta:
next = next + day_delta
days.append(next)
start_day = balloon.start_date
days.append(start_day)
days.append(end)
holiday = []
for purple in days:
pink = purple.day
holiday.append(pink)
return holiday

Python, How to use part of function outside function

How can I use today and returntime in return_fee function?
import datetime
class Movie(object):
def __init__(self,title):
self.title = title
def time_of_return(self):
self.today = today
self.returntime = returntime
today = datetime.datetime.now()
returntime = today + datetime.timedelta(days=30)
def return_fee(Movie):
fee = -2
delta = today - returntime
I would do it like this:
class Movie(object):
def __init__(self,title):
self.title = title
def get_times(self):
now = datetime.datetime.now()
return now, now + datetime.timedelta(days=30)
def time_of_return(self):
now, returntime = self.get_times()
return returntime
def return_fee(self):
fee = -2
now, returntime = self.get_times()
delta = now - returntime
return <whatever based on fee and delta>
If you want time_of_return and return_fee to be instance attributes, call time_of_return from __init__ to set them and then prefix with self:
class Movie(object):
def __init__(self,title):
self.title = title
self.time_of_return()
def time_of_return(self):
self.today = datetime.datetime.now()
self.returntime = today + datetime.timedelta(days=30)
def return_fee(Movie):
fee = None
delta = self.today - self.returntime
# ... presumably do something else
Alternatively (since, in particular, today may change over time), call the function time_of_return from within return_fee and make sure it returns something:
class Movie(object):
def __init__(self,title):
self.title = title
def time_of_return(self):
today = datetime.datetime.now()
returntime = today + datetime.timedelta(days=30)
return today, returntime
def return_fee(Movie):
fee = None
today, returntime = self.time_of_return()
delta = today - returntime
# ... presumably do something else
It's a good idea to indent your code by 4 spaces, by the way. And None (or 0) would be a better default value for fee.
class Movie(object):
def __init__(self,title,today,returntime):#<----
self.title = title
def time_of_return(self):
self.today = today
self.returntime = returntime
today = datetime.datetime.now()
returntime = today + datetime.timedelta(days=30)
def return_fee(Movie):
fee = -2
delta = today - returntime
That's because __init__() is taking arguments that using for class from outside.But, when you use your Movie class, you have to define that arguments.

Categories

Resources