Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7926601
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T18:50:46+00:00 2026-06-03T18:50:46+00:00

I want to calculate a bonus based on the two consecutive months where sales

  • 0

I want to calculate a bonus based on the two consecutive months where sales where the most. So I can iterate a total for every two consecutive months to find the Max value ie get

value = Max[total_between_firstdayMonth1_and_lastDayMonth2, total_between_firstdayMonth2_and_lastDayMonth3, ... , total_between_firstdaySecondToLastMonth_andlastDayLastMonth]

So I might need a list of pairs of datetime objects or something similar.

start= model.Order.order('created').get().created # get the oldest order
end = model.Order.order('-created').get().created # get the newest order

So inbetween start and end I must partition the time in overlapping pairs of consecutive 2 months eg. if first order was in december 2008 and the last order was in november 2011 then the list from where to pick the max should be [total_december2008 + total_january2009, total_january2009 + total_february2009, ... , total_october2011 + total_november2011]

But then how do I get the last day of the second month if I know the start like above? How can I create the list of times and totals?

I might not be able to create the list of totals right away but if I can create the list of starts and ends then I can call a helper function we can assume eg.

total(start_datetime, end_datetime)

Thanks for any help

Update

I think I found how to calculate the time for an example interval where the timeline is from any date to last day next month:

>>> d = date(2007,12,18)
>>> print d
2007-12-18
>>> d + relativedelta(months=2) - timedelta(days=d.day)
datetime.date(2008, 1, 31)

Update 2

I can calculate upto the first level the first duration. Now I only have to generalize it to loop through all the durations and check which was the highest level:

def level(self):
    startdate = model.Order.all().filter('status =', 'PAID').filter('distributor_id =' , self._key.id()).get().created.date()
    last_day_nextmonth =startdate + relativedelta(months=2) - timedelta(days=1)
    if self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth) < 25:
        maxlevel = _('New distributor')
    elif self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)   > 25:
        maxlevel = _('Assistant Teamleader')
    return maxlevel

Update 3

Closer to what I mean is taking the max of some function values from beginning up to now. Basecase can be that last day next month is is the future and the helper function can be recursive but I didn’t have time or help to make it recursive to it only works for the first 2 periods now ie 4 months from start:

def level(self):
    startdate = model.Order.all().filter('status =', 'PAID'
            ).filter('distributor_id =',
                     self._key.id()).get().created.date()
    last_day_nextmonth = startdate + relativedelta(months=2) \
        - timedelta(days=1)
    total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
    if total >= 125:
        level = 5
    elif total >= 75:
        level = 4
    elif total >= 25:
        level = 3
    elif total >= 2:
        level = 2
    else:
        level = 1
    return self.levelHelp(level, last_day_nextmonth + timedelta(days=1))

def levelHelp(self, level, startdate):
    #if startdate in future return level
    last_day_nextmonth = startdate + relativedelta(months=2) \
        - timedelta(days=1)
    total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
    if total >= 125:
        newlevel = 5
    elif total >= 75:
        newlevel = 4
    elif total >= 25:
        newlevel = 3
    elif total >= 2:
        newlevel = 2
    else:
        newlevel = 1
    return level if level > newlevel else newlevel

Update 4

I added the recursion where base case is that next step is in the future, if so it will return the max level:

def level(self):
    startdate = model.Order.all().filter('status =', 'PAID'
            ).filter('distributor_id =',
                     self._key.id()).get().created.date()
    last_day_nextmonth = startdate + relativedelta(months=2) \
        - timedelta(days=1)
    total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
    if total >= 125:
        level = 5
    elif total >= 75:
        level = 4
    elif total >= 25:
        level = 3
    elif total >= 2:
        level = 2
    else:
        level = 1
    return self.levelHelp(level, last_day_nextmonth + timedelta(days=1))

def levelHelp(self, level, startdate):

    last_day_nextmonth = startdate + relativedelta(months=2) \
        - timedelta(days=1)
    total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
    if total >= 125:
        newlevel = 5
    elif total >= 75:
        newlevel = 4
    elif total >= 25:
        newlevel = 3
    elif total >= 2:
        newlevel = 2
    else:
        newlevel = 1

    maxlevel = level if level > newlevel else newlevel

    nextstart = last_day_nextmonth + timedelta(days=1)
    now = datetime.now().date()
    if nextstart > now: #next start in is the future
        return maxlevel
    else: return self.levelHelp(maxlevel, nextstart)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T18:50:47+00:00Added an answer on June 3, 2026 at 6:50 pm

    This sounds like a fine job for functional approach. At the end there is a full working example, but I just want to emphasize the elegance and simplicity of the core function, written in FP style:

    def find_best_two_months(orders):
      first  = lambda x: x[0]
      second = lambda x: x[1]
    
      orders_by_year_and_month = [ 
        ("%04d-%02d" % (date.year, date.month), amount) 
        for date, amount in orders]
    
      sorted_orders = sorted(orders_by_year_and_month, key=first)
    
      totals_by_month = [ 
        (ym, sum(map(second, groupped_orders))) 
        for ym, groupped_orders in groupby(sorted_orders, key=first)]
    
      totals_two_months = [ 
        ( "%s - %s" % (m1[0], m2[0]), m1[1]+m2[1] ) 
        for m1, m2 in zip(totals_by_month, totals_by_month[1:]) ]
    
      return max(totals_two_months, key=second)
    

    Here is a full working example with comments:

    #!/usr/bin/python
    from random import randint
    from datetime import date, timedelta
    from itertools import groupby
    
    """ finding best two months the functional way """
    
    def find_best_two_months(orders):
      """
      Expect a list of tuples of form (date_of_order, amount):
    
      [ (date1, amount1), (date2, amount2), ...]
      """
    
      " helper functions for extracting first or second from tuple "
      first  = lambda x: x[0]
      second = lambda x: x[1]
    
      " converts [(date, amount)] -> [(YYYY-MM, amount)] "
      orders_by_year_and_month = [ ("%04d-%02d" % (date.year, date.month), amount) for date, amount in orders]
    
      " Sorts by YYYY-MM. This step can be omitted if orders were already sorted by date"
      sorted_orders = sorted(orders_by_year_and_month, key=first)
    
      " Compresses orders from the same month, so ve get [(YYYY-MM), total_amount_of_orders]"
      totals_by_month = [ (ym, sum(map(lambda x:x[1], groupped_orders))) 
        for ym, groupped_orders in groupby(sorted_orders, key=first)]
    
      " Zips orders to two month periods"
      totals_two_months = [ ("%s - %s" % (m1[0], m2[0]), m1[1]+m2[1]) for m1, m2 in zip(totals_by_month, totals_by_month[1:]) ]
    
      " Returns two-month period with maximum total amount. If there were many periods with max amount, only the first is returned "
      return max(totals_two_months, key=second)
    
    """ 
    this code is for generating random list of orders 
    and is not a part of the solution 
    """
    MIN_AMOUNT=70
    MAX_AMOUNT=500
    MAX_DAY_SPREAD=5
    
    def gen_order(last_date):
      """ returns (order_date, amount) """
      days = timedelta()
      return (
          last_date+timedelta(days=randint(0, MAX_DAY_SPREAD)),  # new date
          randint(MIN_AMOUNT, MAX_AMOUNT)) # amount
    
    def gen_orders(total, start_date):
      orders = []
      last_date = start_date
      for i in range(total):
        order = gen_order(last_date)
        orders.append(order)
        last_date = order[0]
      return orders
    
    if __name__ == "__main__":
      orders = gen_orders(300, date(2010,1,1)) 
      print find_best_two_months(orders)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to calculate the difference between two datetime.date() dates in years and months.
I want to calculate the total call duration of every contact in given period
I want to calculate total say Sundays,Mondays...Saturdays between two days. I want a do
I want to calculate a new date by adding a number of months to
I want to calculate total memory used by a process in .net. Total memory
I want to calculate the angle between two vectors a and b. Lets assume
I want to calculate the difference between two times, one of which is the
I want to calculate total value in index [0][2], previous value is 0, but
I want to calculate Daylight hours based on given Latitude and Longitude and DateTime
I want to calculate price based on the customer selected options. For example,there are

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.