Exemplo n.º 1
0
def netWorkHours(date1, time1, date2, time2):
    from datetime import datetime, time, date
    from workdays import networkdays

    if time1 > time(18):
        time1 = time(18)
    elif time1 < time(8):
        time1 = time(8)
    
    if time1 > time(18):
        time1 = time(18)
    elif time1 < time(8):
        time1 =time(8)

    
    if date1 == date2:
        return str(timeSub(time2, time1))
    elif date1 < date2:
        if time1 < time2 :
            return str(networkdays(date1,date2) - 1) + 'days ' + str(timeSub(time2, time1))
        elif time1 > time2:
            delta1 = timeSub(time(18), time1)
            print( "delta 1: ",  delta1)
            delta2 = timeSub(time2,time(8))
            print("delta 2: " , delta2)
            return str(networkdays(date1,date2) - 2) + 'days ' + str(delta1 + delta2)
    else: 
        return None
Exemplo n.º 2
0
    def set_status(self, status_str):
        old_status = self.status
        for rs in request_statuses:
            if status_str == rs[1] or status_str == rs[0]:
                self.status = rs[0]
                new_status = self.status

                if old_status == 'S' and (new_status in [
                        'R', 'P', 'F', 'D'
                ]) and self.scheduled_send_date is not None:
                    # Our first response from the agency
                    now = datetime.now(tz=pytz.utc)
                    holidays = self.government.get_holiday_dates
                    self.first_response_time = workdays.networkdays(
                        self.scheduled_send_date, now, holidays)
                    if self.first_response_time == 0:
                        self.first_response_time = 1

                if old_status in ['S', 'R', 'P'] and new_status in [
                        'F', 'D'
                ] and self.scheduled_send_date is not None:
                    now = datetime.now(tz=pytz.utc)
                    holidays = self.government.get_holiday_dates
                    self.lifetime = workdays.networkdays(
                        self.scheduled_send_date, now, holidays)
                    if self.lifetime == 0:
                        self.lifetime = 1
                self.save()
        return self.get_status
Exemplo n.º 3
0
def calculate_column(df):
	for index, row in df.iterrows():
		df.loc[index, 'Received to Submitted'] = wd.networkdays(row['Received'], row['Submitted'])
		df.loc[index, 'Started to Submitted'] = wd.networkdays(row['Started'], row['Submitted'])
		df.loc[index, 'Received to Started'] = wd.networkdays(row['Received'], row['Started'])
		df.loc[index, 'Place'] = row['Type'][0:2]
	return df
Exemplo n.º 4
0
def test_networkdays():
    # test standard networkdays with no holidays or modified weekend
    assert networkdays(date(2015, 8, 1), date(2015, 9, 30), holidays=[]) == 43

    # test with USA's Labor Day
    holidays = [date(2015, 9, 7)]
    assert networkdays(date(2015, 8, 1), date(2015, 9, 30),
                       holidays=holidays) == 42

    # test with short work week (Friday's off as well)
    weekends = (4, 5, 6)
    assert networkdays(date(2015, 8, 1),
                       date(2015, 9, 30),
                       holidays=[],
                       weekends=weekends) == 35

    # test with holidays and short work week
    weekends = (4, 5, 6)
    assert networkdays(date(2015, 8, 1),
                       date(2015, 9, 30),
                       holidays=holidays,
                       weekends=weekends) == 34

    # test with overlapping holiday and weekend
    weekends = (0, 5, 6)
    assert networkdays(date(2015, 8, 1),
                       date(2015, 9, 30),
                       holidays=holidays,
                       weekends=weekends) == 34
Exemplo n.º 5
0
    def handle(self, *args, **options):
        therequests = Request.objects.filter(government__isnull=False)
        for req in therequests.filter(status__in=['R','P','F']):
            mb = MailBox.objects.get(usr=req.author)
            messages = mb.get_threads(req.id)
            contacts = req.contacts.all()
            for msg in messages:
                for contact in contacts:
                    for email in contact.emails.all():
                        if(msg.email_from == email.content):
                            holidays = req.government.get_holiday_dates
                            req.first_response_time = workdays.networkdays(req.scheduled_send_date, msg.dated, holidays)
                            req.save()
                            print "HERE %s %s %s" % (msg.email_from, msg.dated, req.first_response_time)
                            '''
                            TODO
                            add logic to find the last contact date
                            set whether it was overdue
                            add UI element to mark a message as the agency's response
                                (how would this work bc users can forward a message so the date needs to be accurately counted)
                                add a UI field for date input, so you can scroll down to the message click mark this and add the date of the response
                            add UI element to mark a request as part of the official stats
                                can we use groups instead of a flag? that way we can do periodic studies to see how things improve / degrade...
                                would need more of an admin interaface to create a stats group, add requests to it and view stats by group
                            '''

        for req in therequests.filter(status__in=['F']).filter(scheduled_send_date__isnull=False):
            now = datetime.now(tz=pytz.utc)
            holidays = req.government.get_holiday_dates
            req.lifetime = workdays.networkdays(req.scheduled_send_date, now, holidays)
            req.save()
Exemplo n.º 6
0
def vc_alpha(alpha, V, i1, i2, t0, d, tf):

    """
    Calculates the limit value for selling a title, given a
    percentage 'alpha'
    """

    hoje = datetime.date.today()

    Nhoje = (hoje - t0).days

    N = workdays.networkdays(t0, tf)
    Nc = (tf - t0).days

    proxInv = hoje + datetime.timedelta(days=d)

    Nprox = workdays.networkdays(proxInv, tf)
    Nproxc = (tf - proxInv).days

    print "\nN: {0:4d}, N Corr: {1:4d}, N Hoje: {2:4d}, " \
        "N Prox: {3:4d}, N Prox Corr: {4:4d}\n".format(
            N, Nc, Nhoje, Nprox, Nproxc)

    i1d = math.pow(1.0 + i1, 1.0 / util.DIASANO) - 1.0
    i2d = math.pow(1.0 + i2, 1.0 / util.DIASANO) - 1.0

    t1 = util.ir(Nc) + (1.0 - util.ir(Nc)) * math.pow(1.0 + i1d, N)
    t2 = util.ir(Nproxc) + (1.0 - util.ir(Nproxc)) * math.pow(1.0 + i2d, Nprox)

    vLim = (alpha * t1 / (t2 * (1.0 - util.ir(Nhoje))) -
            util.ir(Nhoje) / (1.0 - util.ir(Nhoje))) * V

    return vLim
Exemplo n.º 7
0
def get_contract_days_length(date, how='total'):
    '''Returns the number of workdays in a contract period for the specified 'date' based on VIX futures expiry definition below.
       Expiration Date: The Wednesday that is thirty days prior to the third Friday of the
       calendar month immediately following the month in which the contract expires
            
    Parameters
    ----------
    how : str, 'total' or 'remaining', default: 'total'
        'total' returns the total number of workdays within the contract period. 'remaining' returns the number of workdays remaining in the contract period.
    '''
    if not isinstance(date, datetime.date):
        date = parse(date)
    last_trading_days = get_last_trading_days(date - datetime.timedelta(365), date + datetime.timedelta(365*2), -1)
    next_expiry = next(y for y in sorted(last_trading_days, reverse=False) if y > date)
    last_trading_days = get_last_trading_days(date - datetime.timedelta(365), date + datetime.timedelta(365*2), -1)
    prior_expiry = next(y for y in sorted(last_trading_days, reverse=True) if y <= date)

    nyse_cal = USTradingCalendar()
    mkt_holidays = nyse_cal.holidays() #[dt.date() for dt in nyse_cal.holidays()]
    if how == 'total':
        days_in_contract = workdays.networkdays(prior_expiry, next_expiry, mkt_holidays) - 1
    elif how == 'remaining':
        days_in_contract = workdays.networkdays(date, next_expiry, mkt_holidays) - 1
    else:
        raise ValueError("Unknown parameter how='%s'. Use 'total' or 'remaining'." % how)
    return days_in_contract
    def handle(self, *args, **options):
        therequests = Request.objects.filter(government__isnull=False)
        for req in therequests.filter(status__in=['R', 'P', 'F']):
            mb = MailBox.objects.get(usr=req.author)
            messages = mb.get_threads(req.id)
            contacts = req.contacts.all()
            for msg in messages:
                for contact in contacts:
                    for email in contact.emails.all():
                        if (msg.email_from == email.content):
                            holidays = req.government.get_holiday_dates
                            req.first_response_time = workdays.networkdays(
                                req.scheduled_send_date, msg.dated, holidays)
                            req.save()
                            print "HERE %s %s %s" % (msg.email_from, msg.dated,
                                                     req.first_response_time)
                            '''
                            TODO
                            add logic to find the last contact date
                            set whether it was overdue
                            add UI element to mark a message as the agency's response
                                (how would this work bc users can forward a message so the date needs to be accurately counted)
                                add a UI field for date input, so you can scroll down to the message click mark this and add the date of the response
                            add UI element to mark a request as part of the official stats
                                can we use groups instead of a flag? that way we can do periodic studies to see how things improve / degrade...
                                would need more of an admin interaface to create a stats group, add requests to it and view stats by group
                            '''

        for req in therequests.filter(status__in=['F']).filter(
                scheduled_send_date__isnull=False):
            now = datetime.now(tz=pytz.utc)
            holidays = req.government.get_holiday_dates
            req.lifetime = workdays.networkdays(req.scheduled_send_date, now,
                                                holidays)
            req.save()
def get_weekdays_num_month(start_year, start_month, start_day, end_year, end_month, end_day):
    weekdays_num_month_list = []

    total_workdays_num = wd.networkdays(dt.date(start_year, start_month, start_day), dt.date(end_year, end_month, end_day))

    print("total weekdays between is: {}".format(total_workdays_num))

    for now_year in range(start_year, end_year + 1):
        if start_year < end_year:
            first_month_year = 1
            last_month_year = 12

            if now_year == start_year:
                begin_month = start_month
            else:
                begin_month = first_month_year

            if now_year == end_year:
                finish_month = end_month
            else:
                finish_month = last_month_year
        else:
            begin_month = start_month
            finish_month = end_month

        for now_month in range(begin_month, finish_month + 1):
            print("month is {}".format(now_month))

            first_day_month = 1
            last_day_month = calendar.monthrange(now_year, now_month)[1]

            if now_year == start_year and now_month == start_month:
                begin_day = start_day
            else:
                begin_day = first_day_month

            if now_year == end_year and now_month == end_month:
                finish_day = end_day
            else:
                finish_day = last_day_month

            # how many weekdays in this month
            month_num_weekdays = wd.networkdays(dt.date(now_year, now_month, begin_day), dt.date(now_year, now_month, finish_day))

            # data structure is: current year, current month and total weekdays in this month of the year
            now_month_plan = [now_year, now_month, month_num_weekdays]

            # a list, show the month and how many weekdays
            weekdays_num_month_list.append(now_month_plan)

            print("The number of weekdays in this month is: {}\n".format(month_num_weekdays))

    # how many months in during the time
    month_num = len(weekdays_num_month_list)

    return total_workdays_num, month_num, weekdays_num_month_list
def display_new_messages():

    now = arrow.now()
    end = arrow.get('2019-01-31 00:00:00', 'YYYY-MM-DD HH:mm:ss')
    calc = now - end
    label.setText("Exact time left including weekends: " + str(calc))

    # TODO: add a description label
    label2.setText("Total working days left: " + str(workdays.networkdays(now, end)))

    totalHrsLeft = workdays.networkdays(now, end) * 7.5
    label3.setText("Total working Hrs left: " + str(totalHrsLeft))
Exemplo n.º 11
0
    def _set_due_date(self, cr, uid, inv, context):
        # And, now we have to set the date_due to compy with Sepa stuff.
        # We do this for every invoice
        print "date-due now is", inv.date_due
        if inv.sdd_mandate_id.recurrent_sequence_type == 'recurring':
            # Recurring mandate, setting date to to invoice data, but only if the invoice date is
            # 3 days into the future! Otherwise add 3 working days
            date_invoice = datetime.strptime(inv.date_invoice, DEFAULT_SERVER_DATE_FORMAT)
            difference = workdays.networkdays(date.today(), date_invoice.date())
            print "En het verschil is", difference

            # If invoicedate == today, difference == 1
            # If invoicedate == tomorrow, difference == 2
            # networkdays is inclusive, so workdays.networkdays(date.today(), date.today()) == 1
            # We need a minimum difference of 3 real days, 4 networkdays
            if difference < 5:
                # Difference isn't enough, setting the difference from today date
                date_due = workdays.workday(datetime.now(), 5).date()
            else:
                # Difference is good
                date_due = date_invoice.date()
        else:
            # First mandate, this needs at least six working days, at the SP we decided to pick 14 days,
            # that's ten working days.
            date_invoice = datetime.strptime(inv.date_invoice, DEFAULT_SERVER_DATE_FORMAT)
            difference = workdays.networkdays(date.today(), date_invoice.date())
            print "En het verschil is", difference
            if difference < 7:
                # Difference isn't enough, setting the difference from today date
                date_due = workdays.workday(datetime.now(), 7).date()
            else:
                # Difference is good
                date_due = date_invoice.date()
        print "new date due is", date_due
        date_due = date_due.strftime(DEFAULT_SERVER_DATE_FORMAT)
        print "En als string", date_due
        # Setting new date_due on the invoice:
        # inv.write(cr, uid, inv.id, {'date_due': date_due}, context=context)
        inv.write({'date_due': date_due})
        # inv.date_due = date_due

        # And on the move lines. Only update the receivable line, that's the only line that has a due date

        for move_line in inv.move_id.line_id:
            if move_line.account_id.type == 'receivable':
                move_line.date_maturity = date_due
                # move_line.write(cr, uid, move_line.id, {'date_maturity': date_due}, context=context)
                move_line.write({'date_maturity': date_due})

        return date_due
Exemplo n.º 12
0
def outputcsv(boat):
    if boat["canvasStart"] == "":
        lag1 = "N/A"
        lag2 = max(workdays.networkdays(datetime.datetime.strptime(boat["fabEnd"],"%Y-%m-%d").date(), \
                   datetime.datetime.strptime(boat["paintStart"],"%Y-%m-%d").date(), holidays) -2, 0)
    else:
        lag1 = max(workdays.networkdays(datetime.datetime.strptime(boat["fabEnd"],"%Y-%m-%d").date(), \
                   datetime.datetime.strptime(boat["canvasStart"],"%Y-%m-%d").date(), holidays) -2, 0)
        lag2 = max(workdays.networkdays(datetime.datetime.strptime(boat["canvasEnd"],"%Y-%m-%d").date(), \
                   datetime.datetime.strptime(boat["paintStart"],"%Y-%m-%d").date(), holidays) -2, 0)
    lag3 = max(workdays.networkdays(datetime.datetime.strptime(boat["paintEnd"],"%Y-%m-%d").date(), \
               datetime.datetime.strptime(boat["outfitStart"],"%Y-%m-%d").date(), holidays) -2, 0)
    print('"%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s","%s"' % \
          (boat["job"], boat["fabStart"], boat["fabEnd"], boat["canvasStart"], lag1, boat["canvasEnd"], \
           boat["paintStart"], lag2, boat["paintEnd"], boat["outfitStart"], lag3, boat["outfitEnd"]))
Exemplo n.º 13
0
def sum_transactions(transactions):
    """ Sums transactions into a total of remaining vacation days. """
    workdays_per_year = 250
    previous_date = None
    rate = 0
    day_sum = 0
    for transaction in transactions:
        date, action, value = _parse_transaction_entry(transaction)
        if previous_date is None:
            previous_date = date
        elapsed = workdays.networkdays(previous_date, date, stat_holidays()) - 1

        if action == 'rate':
            rate = float(value) / workdays_per_year
        elif action == 'off':
            elapsed -= 1  # Didn't work that day
            day_sum -= 1  # And we used a day
        day_sum += rate * elapsed

        if action == 'days':
            day_sum = value  # Fixed value as of this entry

        previous_date = date

    return day_sum
Exemplo n.º 14
0
    def _get_number_of_days(self, date_from, date_to, employee_id): 
        holidays = []
        cal =  Senegal()

        #Récupérer les dates de jours fériés validés
        jour_ferie_ids =  self.env['owatrans_rh.ferie'].search([])
        
        if jour_ferie_ids:
            for jour_ferie_id in jour_ferie_ids:
               date_ferie = self.env['owatrans_rh.ferie'].search_read([['id','=',jour_ferie_id.id]], ['date'])[0]['date']
               holidays.append(datetime.strptime(date_ferie,'%Y-%m-%d').date())
        
        dtf = datetime.strptime(date_from,'%Y-%m-%d %H:%M:%S')
        dtt = datetime.strptime(date_to,'%Y-%m-%d %H:%M:%S')
        
        year1 = str(dtf).split("-")[0]
        year2 = str(dtt).split("-")[0]
        
        for i in cal.holidays(int(year1)):
            holidays.append(i[0])
        
        if (year1 != year2): 
            for i in cal.holidays(int(year2)):
                holidays.append(i[0])

        print 'holidays', holidays
        
        diff_day = networkdays(dtf.date(), dtt.date(), holidays, (6,))
        
        return diff_day
Exemplo n.º 15
0
def sum_transactions(transactions):
    """ Sums transactions into a total of remaining vacation days. """
    workdays_per_year = 250
    previous_date = None
    rate = 0
    day_sum = 0
    for transaction in transactions:
        date, action, value = _parse_transaction_entry(transaction)
        if previous_date is None:
            previous_date = date
        elapsed = workdays.networkdays(previous_date, date,
                                       stat_holidays()) - 1

        if action == 'rate':
            rate = float(value) / workdays_per_year
        elif action == 'off':
            elapsed -= 1  # Didn't work that day
            day_sum -= 1  # And we used a day
        day_sum += rate * elapsed

        if action == 'days':
            day_sum = value  # Fixed value as of this entry

        previous_date = date

    return day_sum
Exemplo n.º 16
0
    def available_hours(self):
        end_date = self.cached_due_date
        if end_date is None or self.effort is None:
            # TODO: what is an appropriate amount of effort (man-days) to set
            #       for a task that has no effort or no due date?  Right now
            #       we set at 2 hours (a quarter-day)
            return 0.25 # or 0.0?
        else:
            if type(end_date) is datetime.datetime:
                end_date = end_date.date()
            # get holidays in years covered across today through
            # requested/scheduled date
            holidays = []
            ptor_time = 0.0
            for year in range(datetime.date.today().year, end_date.year+1):
                holiday_dates = [h['date'] for h in Holiday.get_holidays_for_year(year, {'paid_holiday':True})]
                holidays.extend(holiday_dates)
            
                # also add paid time off requests that have been approved as non working days
                if self.assignee:
                    for ptor in PaidTimeOffRequest.objects.filter(Q(pto_start_date__year=year)|Q(pto_end_date__year=year)
                        ).filter(Q(status=PaidTimeOffRequest.APPROVED)|Q(status=PaidTimeOffRequest.PROCESSED)
                        ).filter(user_profile=self.assignee.profile):
                        for i in range((ptor.pto_end_date-ptor.pto_start_date).days):
                            holidays.append(ptor.pto_start_date+datetime.timedelta(days=i))
                        if float(ptor.amount) < 8.0:
                            ptor_time += 8.0 - float(ptor.amount)

            # get number of workdays found in between the today and end_date
            num_workdays = workdays.networkdays(datetime.date.today(),
                                                end_date,
                                                holidays)
            num_workdays = num_workdays - (float(ptor_time)/8.0)
            return 8.0 * max(0.5,num_workdays)
Exemplo n.º 17
0
def remaining_time(reference, expiration):

    if reference == None:
        ref = datetime.now()
    else:
        ref = datetime.combine(reference, time(15))

    ref_excel = excel_date(ref)
    ref_date = datetime(ref.year, ref.month, ref.day)
    ref_date_excel = excel_date(ref_date)
    ref_fraction = ref_date_excel - ref_excel

    expiration_excel = excel_date(expiration)
    expiration_date = datetime(expiration.year, expiration.month,
                               expiration.day)
    expiration_date_excel = excel_date(expiration_date)
    expiration_fraction = expiration_date_excel - expiration_excel

    fraction = expiration_fraction - ref_fraction
    networkingdays = workdays.networkdays(ref.date(), expiration.date(),
                                          holidays)

    remaining_time_in_years = (
        (networkingdays - 1) - fraction) / yeartradingdays
    return remaining_time_in_years
def return_last_day_of_working(year, month) :
    
    if month == 3 :
        if year % 4 == 0 :
            start_date = datetime.datetime(year, month-1, 29)
            end_date = datetime.datetime(year, month, 31)
        else :
            start_date = datetime.datetime(year, month-1, 28)
            end_date = datetime.datetime(year, month, 31)
    elif month is 5 or 7 or 10 or 12 :
        start_date = datetime.datetime(year, month-1, 30)
        end_date = datetime.datetime(year, month, 31)
    elif month == 2 :
        if year % 4 == 0 :
            start_date = datetime.datetime(year, month-1, 31)
            end_date = datetime.datetime(year, month, 29)
        else :
            start_date = datetime.datetime(year, month-1, 31)
            end_date = datetime.datetime(year, month, 28)
    else :
            start_date = datetime.datetime(year, month-1, 31)
            end_date = datetime.datetime(year, month, 30)

    day_num =  workdays.networkdays(start_date, end_date)
    return workdays.workday(start_date, days=day_num)
Exemplo n.º 19
0
    def Parse(self):
        # print("======== Start Parsing ==========")
        # find connections
        tmax = self.Start
        tmin = self.Start
        for t in self.Tasks:
            tt = self.Tasks[t]
            if len(tt.Before) > 0:
                tt.setBefore(self.Tasks[tt.Before])
            if len(tt.After) > 0:
                # print(tt.After)
                for t in tt.After.split(","):
                    tt.setAfter(self.Tasks["%s" % t])
            if tt.Parent != None:
                tt.Parent.addChild(tt)

        # Update times
        for t in self.Tasks:
            tt = self.Tasks[t]
            self.Start = min(self.Start, tt.Start)
            self.End = max(self.End, tt.End)
        self.Duration = workdays.networkdays(self.Start, self.End)
        self.gantt = gantt.Project(name=self.Name)

        for t in self.Tasks:
            tt = self.Tasks[t]
            self.gantt.add_task(tt.makeGanttItem())
Exemplo n.º 20
0
 def number_of_working_days(self):
     if self.db_project.start_date and self.db_project.end_date:
         return networkdays(self.db_project.start_date,
                            self.db_project.end_date,
                            holidays=self.bank_holidays)
     else:
         return 0
Exemplo n.º 21
0
def main(event, context):
    pubsub_message = base64.b64decode(event['data']).decode('utf-8')
    payload_json = json.loads(pubsub_message)

    session = get_session()

    if account := session.query(Account).filter(Account.account_id == payload_json['account_id']).first():
        account_local_time = datetime.now(pytz.timezone('UTC')).astimezone(pytz.timezone(account.time_zone.time_zone_code)).replace(tzinfo=None)
        for janium_campaign in account.janium_campaigns:
            for contact in janium_campaign.contacts:
                contact_info = contact.contact_info
                if cnxn_action := contact.actions.filter(Action.action_type_id == 1).first():
                    continue
                elif cnxn_req_action := contact.actions.filter(Action.action_type_id == 19).first():
                    if kendo_de_action := contact.actions.filter(Action.action_type_id == 22).first():
                        continue
                    else:
                        if campaign_steps := janium_campaign.janium_campaign_steps.filter(Janium_campaign_step.janium_campaign_step_type_id == 4).order_by(Janium_campaign_step.janium_campaign_step_delay).all():
                            if (networkdays(cnxn_req_action.action_timestamp, datetime.utcnow()) - 1) == (campaign_steps[0].janium_campaign_step_delay - 1):
                                if li_profile_url := contact_info['ulinc']['li_profile_url']:
                                    li_profile_id = get_li_profile_id(li_profile_url)
                                    kendo_person = get_kendo_person(li_profile_id)
                                    action_id = str(uuid4())
                                    if work_email := kendo_person['work_email']:
                                        if validate_kendo_email(work_email):
                                            work_email_dict = {
                                                "value": work_email,
                                                "is_valid": True
                                            }
                                        else:
                                            work_email_dict = {
                                                "value": work_email,
                                                "is_valid": False
                                            }
                                        kendo_person['work_email'] = work_email_dict
                                        contact_info['kendo'] = kendo_person
                                        contact.contact_info = contact_info
                                        if new_action := session.query(Action).filter(Action.action_id == action_id).first():
                                            pass
                                        else:
                                            new_action = Action(action_id, contact.contact_id, 22, datetime.utcnow(), None)
                                            session.add(new_action)
                                        session.commit()
                                    if private_email := kendo_person['private_email']:
                                        if validate_kendo_email(private_email):
                                            private_email_dict = {
                                                "value": private_email,
                                                "is_valid": True
                                            }
                                        else:
                                            private_email_dict = {
                                                "value": private_email,
                                                "is_valid": False
                                            }
                                        kendo_person['private_email'] = private_email_dict
                                        contact_info['kendo'] = kendo_person
                                        contact.contact_info = contact_info
                                        if new_action := session.query(Action).filter(Action.action_id == action_id).first():
                                            pass
Exemplo n.º 22
0
def conv_expiry_date(curr_date, expiry, accrual = 'act365', hols = []):
    if expiry < curr_date:
        return 0.0
    year_conv = int(accrual[-3:])
    if year_conv >= 360:
        return float((expiry - curr_date).days + 1)/year_conv
    else:
        return workdays.networkdays(curr_date, expiry, hols) / float(year_conv)
Exemplo n.º 23
0
def conv_expiry_date(curr_date, expiry, accrual='act365', hols=[]):
    if expiry < curr_date:
        return 0.0
    year_conv = int(accrual[-3:])
    if year_conv >= 360:
        return float((expiry - curr_date).days + 1) / year_conv
    else:
        return workdays.networkdays(curr_date, expiry, hols) / float(year_conv)
Exemplo n.º 24
0
    def latency(self):
        """ This method give the latency of the commit in workdays

        Returns:
            int representing the latency of the commit in days
        """
        #return (self.merge - self.start).days
        return networkdays(self.start, self.merge)
Exemplo n.º 25
0
    def at(self, dt):

        days = workdays.networkdays(self.d0, dt)
        t = pow(1.0 + self.taxa_a / 100, 1.0 / 252)

        vf = self.v * pow(t, days)

        return vf
Exemplo n.º 26
0
    def recompra(self,valor):

        data = datetime.date.today()

        days = workdays.networkdays(self.dataIni, data)
        # TODO: verificar se coloco mais 4 dias para compensacao
        nextDays = workdays.networkdays(data,self.dataEnd)

        fullDays = workdays.networkdays(self.dataIni, self.dataEnd)

        rr = pow(self.v * ((1.0 - self.ir(fullDays) / 100.0) * pow(self.t, fullDays) + \
                           self.ir(fullDays) / 100.0 - self.c(fullDays)) / \
                 ((1.0 - self.ir(nextDays) / 100.0) * (valor * (1.0 - self.ir(days) / 100.0) + \
                                                       self.v * (self.ir(days) / 100.0 - self.c(days)))) \
                 - (self.ir(nextDays) / 100.0 - self.c(nextDays)) / (1.0 - self.ir(nextDays) / 100.0), \
                 1.0 / nextDays)

        print("\nDias investidos {0:4d}\nDias restantes {1:4d}\nValor de venda {2:10.2f}\nJuros minimo para recompra {3:10.2f}%\nSe recomprar com tais juros, lucro de {4:10.2f}".format(days, nextDays, valor, (pow(rr, util.DIASANO) - 1.0) * 100.0), 0)
Exemplo n.º 27
0
def working_days_total(user, dt, till=False):
    start = dt_to_date(dt)
    last_day_of_month = calendar.monthrange(start.year, start.month)[1]
    if till and (till.month == dt.month and till.year == dt.year):
        last_day_of_month = till.day
    return workdays.networkdays(
        start_date=date(year=start.year, month=start.month, day=start.day),
        end_date=date(year=start.year, month=start.month, day=last_day_of_month),
        holidays=calendar_holidays(user, dt.year))
Exemplo n.º 28
0
 def num_days(self, upto_today = False):
     '''The number of classes in the semester (from start date to end date
     excluding weekends and ExcludedDates) '''
     excluded_days = self.excludeddate_set.all().values_list('date', flat=True)
     if upto_today:
         last_day = date.today()
     else:
         last_day = self.last_day
     return networkdays(self.first_day, last_day, excluded_days)
Exemplo n.º 29
0
def delta(inicio, final):
    u"""Calula la diferencia entre dos días y detecta si es hábil o natural."""
    if (inicio is None) or (final is None):
        return None
    else:
        if INICIO_PROCESO < inicio < FINAL_PROCESO:
            return (final - inicio).days
        else:
            return networkdays(inicio, final, HOLIDAYS)
Exemplo n.º 30
0
def delta(inicio, final):
    u"""Calula la diferencia entre dos días y detecta si es hábil o natural."""
    if (inicio is None) or (final is None):
        return None
    else:
        if INICIO_PROCESO < inicio < FINAL_PROCESO:
            return (final - inicio).days
        else:
            return networkdays(inicio, final, HOLIDAYS)
Exemplo n.º 31
0
def time2exp(opt_expiry, curr_time):
    curr_date = curr_time.date()
    exp_date = opt_expiry.date()
    if curr_time > opt_expiry:
        return 0.0
    elif exp_date < curr_date:
        return workdays.networkdays(curr_date, exp_date, CHN_Holidays)/BDAYS_PER_YEAR
    else:
        delta = opt_expiry - curr_time 
        return (delta.hour*3600+delta.min*60+delta.second)/3600.0/5.5/BDAYS_PER_YEAR
Exemplo n.º 32
0
    def venda(self,valor,data=datetime.date.today()):
        days = workdays.networkdays(self.dataIni, data)

        vf = valor - (valor - self.v) * (self.ir(days) / 100.0) - self.v * self.c(days)

        lucro = (vf - self.v) / self.v

        lucroaa = pow(1.0 + lucro, util.DIASANO / days) - 1

        print("Valor inicial: {0:10.2f}\nValor final: {1:10.2f}\nLucro: {2:10.9f}\nLucro a.a.: {3:10.9f}".format(self.v, vf, lucro,lucroaa))
Exemplo n.º 33
0
 def _get_interruption_days(self):
     count = 0
     interruptions = self.history.filter(interruption=True)
     for interrupt in interruptions:
         if interrupt.end_date:
             calc = interrupt.end_date - interrupt.start_date
             if calc.days >= 1:
                 work_days = networkdays(interrupt.start_date, interrupt.end_date)
                 count += work_days - 1
     return count
Exemplo n.º 34
0
    def num_days(self, upto_today=False):
        '''The number of classes in the semester (from start date to end date
        excluding weekends and ExcludedDates) '''

        excluded_days = self.excluded_days()
        if upto_today and date.today() < self.last_day:
            last_day = date.today()
        else:
            last_day = self.last_day
        return networkdays(self.first_day, last_day, excluded_days)
Exemplo n.º 35
0
def time2exp(opt_expiry, curr_time):
    curr_date = curr_time.date()
    exp_date = opt_expiry.date()
    if curr_time > opt_expiry:
        return 0.0
    elif exp_date < curr_date:
        return workdays.networkdays(curr_date, exp_date, CHN_Holidays)/BDAYS_PER_YEAR
    else:
        delta = opt_expiry - curr_time 
        return (delta.hour*3600+delta.min*60+delta.second)/3600.0/5.5/BDAYS_PER_YEAR
Exemplo n.º 36
0
 def __init__(self, doc):
     self.pri = doc.get('pri')
     due = doc.get('due')
     if due:
         self.due = datetime.fromisoformat(doc.get('due'))
         self.days = networkdays(datetime.now(), self.due)
     else:
         self.due = None
         self.days = 0
     self.task = doc.get('task')
     self.done = doc.get('done')
Exemplo n.º 37
0
def update_employee_leaves_after_approval(start_date, end_date, emp_id,
                                          leave_type):
    employee = Employees.query.get(emp_id)
    days = workdays.networkdays(start_date, end_date,
                                gazetted_holidays_list(employee.religion))
    if leave_type == "Medical":
        employee.medical_leaves_availed = employee.medical_leaves_availed + days
        employee.medical_leaves_remaining = employee.medical_leaves_remaining - days
    else:
        employee.general_leaves_availed = employee.general_leaves_availed + days
        employee.general_leaves_remaining = employee.general_leaves_remaining - days
Exemplo n.º 38
0
def days_from_date(strdate, business_days):
    """ Returns the number of days between strdate and today. Add one to date
    as date caclulate is relative to time
    """
    currentdate = datetime.today()
    futuredate = datetime.strptime(strdate, '%Y-%m-%d')
    if business_days:
        delta = workdays.networkdays(currentdate, futuredate)
    else:
        delta = (futuredate - currentdate).days + 1
    return delta
Exemplo n.º 39
0
def month_hours(date: datetime.date, business_days: Optional[int]) -> int:
    """Return the number of work hours in the given month."""

    if business_days is None:
        start_date = datetime.date(date.year, date.month, 1)
        end_date = datetime.date(date.year, date.month, month_days(date))
        business_days = workdays.networkdays(start_date, end_date)

    LOGGER.info('Business days=%d (%d hours)', business_days,
                business_days * 8)

    return business_days * 8
Exemplo n.º 40
0
def getRemainingDays(request, stock):
    """ Retorna o numero de dias até o exercício da opcao. NÃO INCLUI O DIA DE HOJE!"""
    serie = stock[4]
    exercise = Exercise.objects.filter(Q(serie=serie,
                                         date__gte=date.today()))[0]
    days = networkdays(date.today(), exercise.date, holidays)
    response = {
        'status': 'ok',
        'days': days - 1,
        'exercise': exercise.date.strftime("%d/%m/%Y")
    }
    return JsonResponse(response, 201)
Exemplo n.º 41
0
    def save(self, *a, **kw):

        self.days_of_leave = networkdays(self.start_date, self.end_date)

        self.status = "Approved"

        obj = employee.objects.get(id = self.employee.id)

        obj.number_of_leave_days_left = obj.number_of_leave_days_left - self.days_of_leave

        obj.save()

        super(leave, self).save(*a, **kw)
Exemplo n.º 42
0
def vacation() -> 'html':
    """View function for vacations"""
    # check if the http request is a POST request
    if request.method == 'POST':
        # query the database
        start_date = datetime.strptime(request.form.get('start_date'),
                                       '%Y-%m-%d')
        end_date = datetime.strptime(request.form.get('end_date'), '%Y-%m-%d')
        dif = networkdays(start_date, end_date)
        user = User.query.filter_by(id=session.get('user_id')).first()
        vacation_days = user.vacation_days
        vacation_days_taken = user.vacation_days_taken
        vacation_days_available = vacation_days - vacation_days_taken
        # do some calculations in order to validate wether the vacation request is valid or not
        if start_date > end_date:
            flash(
                'You selected a start date before your end date! Please try again.',
                category='danger')
            return redirect(url_for('vac.vacation'))
        elif start_date.date() <= date.today():
            flash(
                'You tried to create a vacation requests which starts at a passed date. Please try again.',
                category='danger')
            return redirect(url_for('vac.vacation'))
        else:
            if dif <= vacation_days_available:
                user = User.query.filter_by(id=session.get('user_id')).first()
                req = Vacation(start_date=start_date,
                               end_date=end_date,
                               user=user)
                db.session.add(req)
                db.session.commit()
                # add the vacation request to the database
                flash('Successfully handed in your vacation request.',
                      category='success')
                return redirect(url_for('vac.vacation'))
            else:
                flash(
                    'You selected a period that exceeds your available vacation days!',
                    category='danger')
                return redirect(url_for('vac.vacation'))
    # code executed if the http request is not a POST request
    # return the rendered template which the user can see
    user = User.query.filter_by(id=session.get('user_id')).first()
    requests = Vacation.query.filter_by(user_id=user.id).all()
    return (render_template('vacation.html',
                            user=current_user,
                            requests=requests,
                            roles_id=session.get('roles_id')), 200, {
                                'location': '/vacation'
                            })
Exemplo n.º 43
0
    def get_bdays(self, from_date, to_date):
        from_date = from_date.split('-')
        from_date = datetime.date(year=int(from_date[0]),
                                  month=int(from_date[1]),
                                  day=int(from_date[2]))

        to_date = to_date.split('-')
        to_date = datetime.date(year=int(to_date[0]),
                                month=int(to_date[1]),
                                day=int(to_date[2]))

        bdays = workdays.networkdays(from_date, to_date)

        return bdays
Exemplo n.º 44
0
def test_networkdays():
    # test standard networkdays with no holidays or modified weekend
    assert networkdays(date(2015, 8, 1), date(2015, 9, 30), holidays=[]) == 43

    # test with USA's Labor Day
    holidays = [date(2015, 9, 7)]
    assert networkdays(date(2015, 8, 1), date(2015, 9, 30),
        holidays=holidays) == 42

    # test with short work week (Friday's off as well)
    weekends = (4,5,6)
    assert networkdays(date(2015, 8, 1), date(2015, 9, 30), holidays=[],
        weekends=weekends) == 35

    # test with holidays and short work week
    weekends = (4,5,6)
    assert networkdays(date(2015, 8, 1), date(2015, 9, 30), holidays=holidays,
        weekends=weekends) == 34

    # test with overlapping holiday and weekend
    weekends = (0,5,6)
    assert networkdays(date(2015, 8, 1), date(2015, 9, 30), holidays=holidays,
        weekends=weekends) == 34
Exemplo n.º 45
0
    def set_status(self, status_str):
        old_status = self.status
        for rs in request_statuses:
            if status_str == rs[1] or status_str == rs[0]:
                self.status = rs[0]
                new_status = self.status

                if old_status == 'S' and (new_status in ['R','P','F','D']) and self.scheduled_send_date is not None:
                    # Our first response from the agency
                    now = datetime.now(tz=pytz.utc)
                    holidays = self.government.get_holiday_dates
                    self.first_response_time = workdays.networkdays(self.scheduled_send_date, now, holidays)
                    if self.first_response_time == 0:
                        self.first_response_time = 1


                if old_status in ['S', 'R', 'P'] and new_status in ['F', 'D'] and self.scheduled_send_date is not None:
                    now = datetime.now(tz=pytz.utc)
                    holidays = self.government.get_holiday_dates
                    self.lifetime = workdays.networkdays(self.scheduled_send_date, now, holidays)
                    if self.lifetime == 0:
                        self.lifetime = 1
                self.save()
        return self.get_status
Exemplo n.º 46
0
def vacation_duration(user, start, end, accounting=False):
    """ Calculate duration of vacation in number of days
    accounting: for calculating days total based on Finnish law
    """
    start, end = dt_to_date(start), dt_to_date(end)
    years = list(set([start.year, end.year]))
    duration = workdays.networkdays(
        start_date=date(year=start.year, month=start.month, day=start.day),
        end_date=date(year=end.year, month=end.month, day=end.day),
        holidays=calendar_holidays(user, years))
    if accounting:
        # for Finnish accounts: every full week, a sixth vacation day is used
        if user.account_id and user.account.country==u'Finland':
            duration += int(duration/5)
    return duration
Exemplo n.º 47
0
 def cache_workdays(self, force=False):
     '''Compute the number of work-days between started_on and dev_done_on
        and prod_done_on, and store on self.'''
     if force or (self.started_on and ((
             self.dev_done_on and self.dev_done_workdays is None) or (
             self.prod_done_on and self.prod_done_workdays is None))):
         days_off = set([v.date for v in self.user.vacation])
         days_off |= set([h.date for h in Holiday.query.all()])
         for stop,cache in (('dev_done_on', 'dev_done_workdays'),
                            ('prod_done_on', 'prod_done_workdays')):
             stop = getattr(self, stop)
             if self.started_on is not None and stop is not None:
                 setattr(self, cache, networkdays(self.started_on, stop,
                                                  holidays=days_off))
             elif force:
                 setattr(self, cache, None)
     return self.dev_done_workdays, self.prod_done_workdays
    def handle(self, *args, **options):
        # Increment days outstanding for requests not rejected/fulfilled
        therequests = Request.objects.filter(status__in=['S','R','P'])
        now = datetime.now(tz=pytz.utc)


        for request in therequests:
            try: 
                last_contact_date = request.last_contact_date
                holidays = request.government.get_holiday_dates

                if not last_contact_date and request.scheduled_send_date:
                    # Just use the send date as last_contact_date if we don't have one set
                    last_contact_date = request.last_contact_date = request.scheduled_send_date
                request.days_outstanding = workdays.networkdays(last_contact_date, now, holidays)

                request.save()
            except Exception as e:
                logger.error(e)
Exemplo n.º 49
0
def process_BOM(market_data, mkt_deps):
    mdate = market_data['market_date']
    if 'COMFwd' not in market_data:
        return
    for fwd_idx in market_data['COMFwd']:
        crv_info = cmq_crv_defn.COM_Curve_Map[fwd_idx]
        if crv_info['exch'] in ['SGX', 'LME', 'NYM']:
            fwd_quotes = market_data['COMFwd'][fwd_idx]
            if (fwd_quotes[0][0] < mdate):
                spotID = crv_info['spotID']
                if spotID == crv_info['instID']:
                    spotID = spotID + '.fut_daily'
                else:
                    spotID = spotID + '.spot_daily'
                if spotID not in mkt_deps['COMFix']:
                    continue
                hols = getattr(misc, crv_info['calendar'] + '_Holidays')
                bzdays = workdays.networkdays(fwd_quotes[0][0], fwd_quotes[0][1], hols)
                past_fix = [ quote[1] for quote in market_data['COMFix'][spotID] if (quote[0] <= mdate) and (quote[0] >= fwd_quotes[0][0])]
                if bzdays > len(past_fix):
                    fwd_quotes[0][2] = (fwd_quotes[0][2] * bzdays - sum(past_fix))/(bzdays - len(past_fix))
Exemplo n.º 50
0
    def __caso1(self):
    
        fullDays = workdays.networkdays(self.dataIni, self.dataEnd)

        return self.v
Exemplo n.º 51
0
def GetDataTransaction(config,parameters,returns):
  global addFilter
  
  helper = phelper.PObjectHelper(config)
  CURRSYMBOL = CreateCurrencyDict(config)
  
  param = parameters.FirstRecord
  
  status = returns.CreateValues(
    ['Is_Err',0],
    ['Err_Message',''],
    ['Cabang',''],
    ['Tanggal',''],
    ['TotalAmount',0.0],
    ['ZakatBalance',0.0],
    ['InfaqBalance',0.0],
    ['WakafBalance',0.0],
    ['AmilBalance',0.0],
    ['OtherBalance',0.0],
    ['WorkDays',0],    
  )
  
  dsData = returns.AddNewDatasetEx(
    'ReportData',
    ';'.join([
      'TransactionDate: datetime',
      'TransactionDateStr: string',
      'ReferenceNo: string',      
      'AccountName: string',
      'Description: string',
      'Amount: float',
      'CurrencyCode: string',
      'Rate: float',
      'EkuivalenAmount: float',                  
      'AuthStatus: string',
      'Channel:string',
      'FundEntity: string',
      'SponsorName: string',
      'VolunteerName: string',      
      'Inputer: string',
      'Marketer: string',
      'BranchName: string',
      'TransactionNo: string',      
    ])
  )
  
  try:
    corporate = helper.CreateObject('Corporate')
    BranchCode = None
    Cabang = '' 
    if param.IsAllBranch == 'F' :
      BranchCode = param.GetFieldByName('LBranch.BranchCode') #config.SecurityContext.GetUserInfo()[4]
      oBranch = helper.GetObject('Branch',BranchCode)
      #CabangInfo = corporate.GetCabangInfo(BranchCode)
      Cabang = '%s - %s' % (BranchCode,oBranch.BranchName)
      if param.IsIncludeChildBranch == 'T' :
        Cabang += " dan KCP"
      
    aBeginDate = param.BeginDate
    aEndDate = param.EndDate
      
    if aBeginDate == aEndDate:
       Tanggal = '%s' % config.FormatDateTime('dd mmm yyyy', aBeginDate)
    else:    
       Tanggal = '%s s.d. %s' % (
                   config.FormatDateTime('dd mmm yyyy', aBeginDate),
                   config.FormatDateTime('dd mmm yyyy', aEndDate) 
                 )
                 
    res = GetReportData(config, param)
    
    MarketerList = {}
    TotalAmount = 0.0
    while not res.Eof:
      recData = dsData.AddRecord()
      aDate = res.ActualDate
      recData.TransactionDateStr = '%2s-%2s-%4s' % (str(aDate[2]).zfill(2), 
                                                 str(aDate[1]).zfill(2), 
                                                 str(aDate[0]))
      recData.ReferenceNo = res.ReferenceNo
      recData.AccountName = res.AccountName
      recData.Description = res.Description

      # if res.CurrencyCode != res.TransCurrencyCode and res.CurrencyCode == '000':
      #   recData.CurrencyCode = res.TransCurrencyName #CURRSYMBOL[res.TransCurrencyCode]
      #   recData.Rate = res.TransRate
      #   recData.Amount      = res.Amount / res.TransRate
      # else :
      #   recData.CurrencyCode = res.CurrencyName #CURRSYMBOL[res.CurrencyCode]
      #   recData.Rate = res.Rate
      #   recData.Amount      = res.Amount
      # # end if
      
      Amount , Rate, CurrencyName = GetAmount(res)
      recData.CurrencyCode = CurrencyName #CURRSYMBOL[res.CurrencyCode]
      recData.Rate         = Rate
      recData.Amount       = Amount
      
      recData.EkuivalenAmount = res.EkuivalenAmount
      recData.Inputer     = res.Inputer
      recData.AuthStatus  = res.AuthStatus      
      recData.SponsorName = res.DonorName      
      recData.Channel     = res.Channel
      recData.Fundentity  = res.FundEntity
      recData.BranchName  = res.BranchName
      recData.TransactionNo = res.TransactionNo
      
      TotalAmount += res.EkuivalenAmount
      # Get VolunteerName
      VName = (res.VolunteerName or '')[:19]
      #oVT = helper.GetObject('VolunteerTransaction',res.TransactionItemId)
      #if not oVT.isnull :
      #   VName = oVT.LVolunteer.VolunteerName
      recData.VolunteerName = VName
      
      
      # Get SponsorName / DonorName
      SName = res.DonorName or ''
#       oST = helper.GetObject('SponsorTransaction',res.TransactionItemId)
#       if not oST.isnull :
#          oDonor = helper.CreateObject('ExtDonor')
#          oDonor.GetData(oST.SponsorId)
#          SName = oDonor.full_name
#          #SName = oST.LSponsor.Name 
      if SName.strip() == '' :
        SName = res.Full_Name
              
      recData.SponsorName = SName
      # Get MarketerName
      recData.Marketer = res.MarketerName or ''
      # if res.MarketerId not in [0,'',None]:
      #   if MarketerList.has_key(res.MarketerId):
      #     recData.Marketer = MarketerList[res.MarketerId]
      #   else:
      #     oMarketer = helper.GetObject('Marketer',res.MarketerId)
      #     if not oMarketer.isnull :
      #       recData.Marketer = oMarketer.Full_Name
      #       MarketerList[oMarketer.MarketerId] = oMarketer.Full_Name        
        
      res.Next()
    #-- while
    
    # Get Balance
    
    status.ZakatBalance = FundEntityBalance(config,BranchCode,aBeginDate,1,addFilter)    
    status.InfaqBalance = FundEntityBalance(config,BranchCode,aBeginDate,2,addFilter)
    status.WakafBalance = FundEntityBalance(config,BranchCode,aBeginDate,3,addFilter)
    status.AmilBalance = 0.0 #FundEntityBalance(config,BranchCode,aBeginDate,4,addFilter) #+ AmilBalance(config,BranchCode,aBeginDate,addFilter)   
    status.OtherBalance = FundEntityBalance(config,BranchCode,aBeginDate,5,addFilter)

      
    status.TotalAmount = TotalAmount
    status.Cabang = Cabang
    status.Tanggal = Tanggal
    sY,sM,sD = config.ModLibUtils.DecodeDate(aBeginDate)[:3]
    eY,eM,eD = config.ModLibUtils.DecodeDate(aEndDate)[:3]
    status.WorkDays = workdays.networkdays(
                 datetime.date(sY,sM,sD),
                 datetime.date(eY,eM,eD)
                 )
    
  except:
    status.Is_Err = 1
    status.Err_Message = str(sys.exc_info()[1])
Exemplo n.º 52
0
if args.previousHours > 0:
    totalHours += float(args.previousHours)
    print args.previousHours + " hours were not calculated in YTD burn rate because their daily duration is unknown!"

print "Total Billable Hours: " + ('%.2f' % totalHours)
print "YTD Burn Rate: " + ('%.2f' % ytdBurnRate)

today = datetime.datetime.now()
lastDayOfYear = datetime.datetime(today.year, 12, 31)

print "Today is " + str(today) + " - Last Day of year is " + str(lastDayOfYear)

vacationDays = []
if args.vacationDays is not None:
    print "Considering Vacation Days -> " + args.vacationDays
    vacationDays = [datetime.datetime.strptime(n, '%Y%m%d') for n in str(args.vacationDays).split(",")]
    print str(len(vacationDays)) + " Vacation days will be taken into consideration"

# holidays.append(datetime.datetime.strptime('20141225', "%Y%m%d"))

numWorkDays = workdays.networkdays(today, lastDayOfYear, vacationDays)
print str(numWorkDays) + " work days remaining"

eighteenRemHours = 1880 - totalHours
fifteenRemHours = (1880 * 0.85) - totalHours
tenRemHours = (1880 * .80) - totalHours

print "\n"
print "18% hours remaining " + str(eighteenRemHours) + " burn rate required " + str(eighteenRemHours / numWorkDays) + " bonus after 30% tax: " + str((int(salary) * 0.18) * .70)
print "15% hours remaining " + str(fifteenRemHours) + " burn rate required " + str(fifteenRemHours / numWorkDays) + " bonus after 30% tax: " + str((int(salary) * 0.15) * .70)
print "10% hours remaining " + str(tenRemHours) + " burn rate required " + str(tenRemHours / numWorkDays) + " bonus after 30% tax: " + str((int(salary) * 0.10) * .70)
Exemplo n.º 53
0
#
# Get the time delta for hours.
# Usage: timedelta.py  145.5
#
# get workdays: pip install workdays

from datetime import date, datetime,timedelta
from workdays import networkdays
import sys

HOUR_PER_DAY = 8
PERCENTAGE = 0.1    # 0.1 = 10%; 0.2 = 20%

if len(sys.argv) < 2:
    print "Pass number of hours worked"
    sys.exit(1)

hours_done = float( sys.argv[1] )

currentDate  = date.today()
firstOfMonth = date(currentDate.year, currentDate.month, 1)

days = networkdays(firstOfMonth, currentDate)
expected_hour = days * HOUR_PER_DAY

percentage_delta = (expected_hour - hours_done) / hours_done
time_delta = ( expected_hour / (1+PERCENTAGE) ) - hours_done

print("percentage_delta = %0.4f" % percentage_delta)
print("time delta (Positive is time owed to company) = %0.4f" % time_delta)
Exemplo n.º 54
0
#Active Days is defined as number of days user used the product at least once.
activedays = []
activitylevel = []
interactionperday = []
count = 0

numberofusers = len(users["ACCOUNT_ID"])

for i in users["ACCOUNT_ID"]:
    #print("User: "******" " + "Total Interaction: " + str(len(d1[d1["ACCOUNT_ID"] == i])))
    company.append(d1[d1["ACCOUNT_ID"] == i]["COMPANY_ID"].max())
    companylastdate.append(d1[d1["COMPANY_ID"] == company[count]]["DATETIME"].max())
    totalinteraction.append(len(d1[d1["ACCOUNT_ID"] == i]))
    firstdate.append(d1[d1["ACCOUNT_ID"] == i]["DATETIME"].min())
    lastdate.append(d1[d1["ACCOUNT_ID"] == i]["DATETIME"].max())
    totalcompanydate.append(workdays.networkdays(firstdate[count], companylastdate[count]))
    activedays.append(len(d1[d1["ACCOUNT_ID"]== i]["JUSTDATE"].drop_duplicates()))
    activitylevel.append(float(activedays[count])/totalcompanydate[count])
    interactionperday.append(totalinteraction[count]/activedays[count])
    count = count + 1

users["Company"] = company
users["Total Interaction"] = totalinteraction
users["First Date"] = firstdate
users["Last Date"] = lastdate
users["Last Company Date"] = companylastdate
users["Total Company Days"] = totalcompanydate
users["Active Days"] = activedays 
users["Interaction Per Day"] = interactionperday
users["Activity Level"] = activitylevel
Exemplo n.º 55
0
def analyze():
    import pandas as pd
    import numpy as np
    import statsmodels.api as sm
    import statsmodels.formula.api as smf
    from workdays import networkdays
    import plotly.plotly as py
    import os

    df_adv = pd.read_csv(data_path)
    if 'TotalTAT' not in df_adv.columns:
        tat = df_adv.apply(lambda row: networkdays(pd.to_datetime(row['SUBMIT_DATE']), pd.to_datetime(row['RECEIPT_DATE'])) if row['SUBMIT_DATE'] is not None and row['RECEIPT_DATE'] is not None else None, axis=1)
        tat = tat.apply(lambda x: x if x >= 0 else None)
        tat = pd.DataFrame(tat, columns = ['TotalTAT'])
        df_adv = pd.concat([df_adv, tat], axis=1)
    if 'RPM' not in df_adv.columns:
        df_adv['RPM'] = df_adv['ERF_TYPE'] - 1


    py.sign_in('dyp93', 'ax2h1t1kzc')

    trace0 = Box(
        y= df_adv['TotalTAT'][df_adv['RPM']==0],
        name = 'RPMs',
        boxpoints='all',
        jitter = 0.9,
        pointpos = 1.8,
        marker = Marker(color = 'rgb(8, 81, 156)',
            )

    )

    trace1 = Box(
        y = df_adv['TotalTAT'][df_adv['RPM']==1],
        name = 'ERFs',
        boxpoints='all',
        jitter = 0.9,
        pointpos = 1.8,
        marker = Marker(color = 'rgb(40, 180, 220)'
        )
    )

    data = Data([trace0,trace1])
    
    layout = Layout(
            yaxis = YAxis(
                title = 'number of days',
                range = [0, 60],
                zeroline = True,
            ),
            width = 1000,
            height = 1000,
        )

    script_dir = os.path.dirname(__file__)
    rel_data = "../static/plot.png"
    img_path = os.path.join(script_dir, rel_data)


    fig = Figure(data =data, layout=layout)
    py.image.save_as(fig, img_path)


    #formula: response = constant + predictor + predictor + predictor + predictor(categorical)
    est = smf.ols(formula = 'TotalTAT ~ C(RPM)', data=df_adv).fit()

    return est
Exemplo n.º 56
0
 def get_num_hours(self):
     return networkdays(self.start_date, self.end_date)