Ejemplo n.º 1
0
def days_left(relative=False):
    """
    Calculates the number of full days left between the event date and the current one. It accepts a 'relative'
    parameter that modifies the result to either return the total number of days (accounting for years and months left
    too) or only the number of days left within a single month (and accounting by the different lengths of each month
    throughout the year, i.e. 28, 29, 30, or 31).

    :param relative: Indicates whether the result asked should only return days within a month or in total. This
    parameter is necessary when displaying a 'summary' string that list years, months and days.
    :type relative: bool
    :return: If the 'relative' parameter was True, return the days left between the target (event) day and today but
    only within the current calendar month. If False, return the total days left between the event day and today
    :rtype: int
    """

    # Check whether the user requested days difference 'relative' to the current month or in total
    if relative:
        # Get current day from the system date
        now = get_now()
        today = now.day

        # Get the number of days that this month have in total
        days_this_month = calendar.monthlen(year=now.year, month=now.month)

        # Calculate the days difference by adding the day of the event with the amount of days left till the end of
        # this month
        delta = (leave_date.day + (days_this_month - today)) % days_this_month
    else:
        # If the user only requested the total number of days, calculate it including years and months
        delta = get_delta().days

    return delta
Ejemplo n.º 2
0
def preprocessor_en4_025d(xds):
    from numpy import arange
    from pandas import date_range
    from calendar import monthlen
    from utils.gridding_utils import center_coords_gmt

    # creating time array
    year = xds.time.to_index().year.unique().values[0]
    month = xds.time.to_index().month.unique().values[0]
    ndays = monthlen(year, month)
    time = date_range(f'{year}-{month}-01', f'{year}-{month}-{ndays}')

    xds = xds.sel(depth=0, method='nearest').drop('depth')
    xds = center_coords_gmt(xds, verbose=False)

    # interpolating data to quarter degree
    xds = (xds.interp(
        lat=arange(-89.875, 90, .25),
        lon=arange(-179.875, 180, .25),
        method='linear').roll(lon=720, roll_coords=False).interpolate_na(
            dim='lon',
            limit=10).roll(lon=-720,
                           roll_coords=False).reindex(time=time,
                                                      method='nearest'))

    return xds
Ejemplo n.º 3
0
def is_date(day1, month2, year3):
    a = str(calendar.monthlen(year3, month2))
    a = int(a)
    if (day1) <= a:
        return True
    else:
        return False
Ejemplo n.º 4
0
    def _get_where_expression(self):
        where_expression = ''
        if self.day:
            where_expression += 'created_at = %(created_at)s'
            self._values['created_at'] = self.day.strftime(FORMAT)
        elif self.month:
            last_day_of_month = calendar.monthlen(self.month.year,
                                                  self.month.month)
            date_start = self.month.strftime(FORMAT)
            date_end = self.month.replace(
                day=last_day_of_month).strftime(FORMAT)
            where_expression += f'created_at between %(date_start)s and %(date_end)s'
            self._values['date_start'] = date_start
            self._values['date_end'] = date_end

        if self.id:
            where_expression += 'id = %(id)s and '
            self._values['id'] = self.id
        if self.uid:
            where_expression += 'uid = %(uid)s and '
            self._values['uid'] = self.uid
        if self.action:
            where_expression += 'action = %(action)s and '
            self._values['action'] = self.action

        return where_expression
Ejemplo n.º 5
0
    def month(self, execution_times, month_of_year):
        from datetime import date
        year = date.today().year

        from calendar import monthlen
        monthLength = monthlen(year, month_of_year)

        return monthLength * (self.app_execution(execution_times))
Ejemplo n.º 6
0
def get_dates(ym):
    worklist = []
    year = int(ym.split('/')[0])
    month = int(ym.split('/')[1].lstrip("0"))
    num = calendar.monthlen(year, month)
    for day in range(1, num + 1):
        if calendar.weekday(year, month, day) < 5:
            date = "%d/%02d/%02d" % (year, month, day)
            worklist.append(date)
    return worklist
Ejemplo n.º 7
0
    def __init__(self, **args):
        super(SecondPage, self).__init__(**args)

        # assigning day of month and day of week to one button
        # week-day str, month-day int
        self.data = [{
            'text': ' |  ' + str(data.strftime("%A  %d")).upper(),
            'id': str(data)
        } for data in (date(2020, 5, i)
                       for i in range(1,
                                      calendar.monthlen(2020, 5) + 1))]
Ejemplo n.º 8
0
def get_months_dates(startmonth, length, month, year):
    # This returns list of dates of specified lengths of months.
    target = datetime.date(year, month, 1)
    lst = []

    for h in range(startmonth, startmonth + length, 1):
        current = target + relativedelta(months=h)
        for i in range(1, calendar.monthlen(current.year, current.month) + 1):
            d = datetime.date(current.year, current.month, i)
            lst.append(d.strftime("%m/%d/%Y 00:00:00"))
    return lst
    def form_valid(self, form):
        monthly = form.save()

        # その月が何日あるか取得
        days = calendar.monthlen(monthly.year, monthly.month)

        # 日付の数だけ日のデータを作成しておく
        for day in range(1, days+1):
            Daily.objects.create(month=monthly, day=day)

        return redirect('app:monthly_update', pk=monthly.pk)
Ejemplo n.º 10
0
def calculateDurationPerHour(entryInitialHour, entryFinalHour, screenFormCreateLog, initialDate, infoToSave):
    if entryInitialHour.get() and entryFinalHour.get():
        try:
            initialHour = int(entryInitialHour.get().split(':')[0])
            initialMinutes = int(entryInitialHour.get().split(':')[1])
        except Exception:
            tk.messagebox.showerror(title='Error hora inicial', message='La hora inicial no presenta un format correcte --> hh:mm. Per exemple: 10:30.')
            screenFormCreateLog.wm_attributes("-topmost", 1)
            screenFormCreateLog.focus_force()
        try:
            finalHour = int(entryFinalHour.get().split(":")[0])
            finalMinutes = int(entryFinalHour.get().split(":")[1])
        except Exception:
            tk.messagebox.showerror(title="Error hora final", message="La hora final no presenta un format correcte --> hh:mm. Per exemple: 11:40.")
            screenFormCreateLog.wm_attributes("-topmost", 1)
            screenFormCreateLog.focus_force()
        
        initialTime = "{}:{}".format(initialHour, initialMinutes)
        finalTime = "{}:{}".format(finalHour, finalMinutes)
        dtInitialTime = datetime.datetime.strptime(finalTime, "%H:%M")
        dtFinalTime = datetime.datetime.strptime(initialTime, "%H:%M")
        if dtFinalTime <= dtInitialTime:
            tdelta = dtInitialTime - dtFinalTime
        else:
            initialTime = "{}-{}-{} {}:{}".format(initialDate.day, initialDate.month, initialDate.year, initialHour, initialMinutes)
            if initialDate.day == 31 and initialDate.month == 12:
                finalTime = "{}-{}-{} {}:{}".format(1, 1, initialDate.year+1, finalHour, finalMinutes)
            else:
                if calendar.monthlen(initialDate.year, initialDate.month) == initialDate.day:
                    finalTime = "{}-{}-{} {}:{}".format(1, initialDate.month+1, initialDate.year, finalHour, finalMinutes)
                else:
                    finalTime = "{}-{}-{} {}:{}".format(initialDate.day+1, initialDate.month, initialDate.year, finalHour, finalMinutes)
            
            
            dtInitialTime = datetime.datetime.strptime(finalTime, "%d-%m-%Y %H:%M")
            dtFinalTime = datetime.datetime.strptime(initialTime, "%d-%m-%Y %H:%M")
            tdelta = dtInitialTime - dtFinalTime
        
        seconds = tdelta.total_seconds()
        hours = seconds // 3600
        minutes = (seconds % 3600) // 60
        seconds = seconds % 60
        infoToSave['hora'] = str(int(hours))
        infoToSave['minuts'] = str(int(minutes))
        infoToSave['segons'] = str(int(seconds))
        tk.messagebox.showinfo(title="Temps calculat", message="{}h:{}m:{}s".format(infoToSave['hora'], infoToSave['minuts'], infoToSave['segons']))
        screenFormCreateLog.wm_attributes("-topmost", 1)
        screenFormCreateLog.focus_force()
    else:
        tk.messagebox.showerror(title="Falten camps per omplir!", message="Cal omplir els dos camps per calcular la durada.")
        screenFormCreateLog.wm_attributes("-topmost", 1)
        screenFormCreateLog.focus_force()
Ejemplo n.º 11
0
def monthdelta(date: datetime, delta: int) -> datetime:
    '''
    same with timedelta, but add or sub with months
    :param date:
    :param delta:
    :return:
    '''
    new_year, new_month = date.year, date.month
    func_offmonth = prevmonth if delta < 0 else nextmonth
    for _ in range(0, abs(delta)):
        new_year, new_month = func_offmonth(new_year, new_month)
    new_day = min(date.day, monthlen(new_year, new_month))
    return date.replace(day=new_day, month=new_month, year=new_year)
Ejemplo n.º 12
0
def send_form(message: telebot.types.Message):
    # Create a form object and set a read-only parameter(s)
    # UserForm(username=message.from_user.username) would do the same
    form = UserForm()
    form.username = message.from_user.username

    # Prepare a list of days of current month
    now = datetime.datetime.now()
    month_days_num = calendar.monthlen(now.year, now.month)
    month_days_list = [str(n + 1) for n in range(month_days_num)]
    # Set choices for this exact
    form.fields.day_of_month.choices = month_days_list

    form.send_form(message.chat.id)
Ejemplo n.º 13
0
def testDate():
    # 获取年、月
    this_year = datetime.now().year
    this_month = datetime.now().month

    date_list = [[
        this_year, this_month,
        calendar.monthlen(this_year, this_month)
    ]]
    for i in range(5):
        year_month_days = list(calendar.prevmonth(this_year, this_month))
        this_month = this_month - 1
        if this_month <= 0:
            this_month = 12
            this_year = this_year - 1
        year_month_days.append(calendar.monthlen(this_year, this_month))
        date_list.append(year_month_days)

    for date_tuple in date_list:
        if date_tuple[1] < 10:
            date_tuple[1] = "0" + str(date_tuple[1])

    print(date_list)
Ejemplo n.º 14
0
def calendar_month_range(date):
    """Given a Datetime.date object, returns a tuple containing the first
    monday and the last sunday of the given month, in format YYYY-MM-DD."""

    # Get day 1 from current month, then get monday of that week
    first_monday = date.replace(day=1).date()
    first_monday += datetime.timedelta(days=-first_monday.weekday())

    # Get last day from current month, then get sunday of that week
    last_sunday = date.replace(
        day=calendar.monthlen(date.year, date.month)).date()
    last_sunday += datetime.timedelta(days=6 - date.weekday())

    return first_monday.isoformat(), last_sunday.isoformat()
Ejemplo n.º 15
0
    def get_past_range(self, date_range):
        if date_range:
            if date_range == "today":
                date = datetime.now().date() - timedelta(days=1)
                start_date = datetime.combine(date, time.min)
                end_date = datetime.combine(date, time.max)
                return start_date, end_date, ""

            elif date_range == "yesterday":
                date = datetime.now().date() - timedelta(days=2)
                start_date = datetime.combine(date, time.min)
                end_date = datetime.combine(date, time.max)
                return start_date, end_date, ""

            elif date_range == "7days":
                date = datetime.now().date()
                start_date = date - timedelta(days=13)
                end_date = date - timedelta(days=6)
                start_date = datetime.combine(start_date, time.min)
                end_date = datetime.combine(end_date, time.max)
                return start_date, end_date, ""

            elif date_range == "30days":
                date = datetime.now().date()
                start_date = date - timedelta(days=60)
                end_date = date - timedelta(days=30)
                start_date = datetime.combine(start_date, time.min)
                end_date = datetime.combine(end_date, time.max)
                return start_date, end_date, ""

            elif date_range == "last_month":
                date = datetime.now().date()
                date = date - timedelta(days=60)
                y, m = calendar.prevmonth(date.year, date.month)
                start_date = datetime(y, m, 1)
                end_date = datetime(y, m, calendar.monthlen(y, m))
                end_date = datetime.combine(end_date, time.max)
                return start_date, end_date, ""

            else:
                try:
                    start_date, end_date = self.parse_datetime(date_range)
                    return start_date, end_date, ""
                except Exception as e:
                    return "", "", create_error_response(
                        {"Msg": "Invalid date range"})
        else:
            start_date, end_date, error = self.get_default_date_range()
            return start_date, end_date, error
Ejemplo n.º 16
0
def calculate(right_pay, paid_amount, arrears_choice, wef, end_date, receipt):
    # SANITIZE INPUTS
    getrightPay = myValidator(right_pay)
    getwrongPay = myValidator(paid_amount)
    tarrears = arrears_choice.get()

    rightPay = m_round(getrightPay, trac=0.05)
    wrongPay = m_round(getwrongPay, trac=0.05)

    toPay = float(rightPay - wrongPay)
    startdate = datetime.strptime(wef.get(), '%m/%d/%y').date()
    enddate = datetime.strptime(end_date.get(), '%m/%d/%y').date()

    nodays = abs(enddate - startdate).days + 1

    daysInMonth = monthlen(enddate.year, enddate.month)

    arrears = daysCalculator(nodays, toPay, daysInMonth)

    receipt.insert(
        END, "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tARREARS\n")
    receipt.insert(
        END,
        "\t\t____________________________________________________________________________\n"
    )
    receipt.insert(
        END, "\t\tDESCRIPTION:\t" + arrears_choice.get() +
        "\t\t\tDAYS TO PAY:\t" + str(nodays) + "\n\n")
    receipt.insert(
        END, "\t\tW.E.F:\t" + str(startdate) + "\t\t\tEND DATE:\t" +
        str(enddate) + "\n\n")
    receipt.insert(
        END, "\t\tRIGHT PAY:\t" + str(rightPay) + "\t\t\tAMOUNT PAID:\t" +
        str(wrongPay) + "\n")
    receipt.insert(
        END,
        "\t\t____________________________________________________________________________\n"
    )
    receipt.insert(END, "\t\tARREARS\t" + str(arrears) + "\n")
    receipt.insert(
        END,
        "\t\t--------------------------------------------------------------------------------------------\n"
    )

    genSheet(tarrears, nodays, startdate, enddate, rightPay, wrongPay, arrears)
Ejemplo n.º 17
0
def preprocessor_ecco4_mxldepth_mon2day_05to025(xds):
    import re
    from numpy import arange
    from xarray import DataArray
    from pandas import date_range
    from calendar import monthlen

    # check correct_file
    fname = xds.encoding['source']  # MXLDEPTH_1994_01
    if re.findall('MXLDEPTH_[12][09][0-9][0-9]_[01][0-9]', fname):
        pass
    else:
        raise UserWarning(
            'Not the correct input file for ECCO4 MXLDEPTH processing')

    xda = xds['MXLDEPTH']

    # fixing the i x j indexing to lat and lons
    xda_050m = DataArray(xda.values,
                         dims=['time', 'lat', 'lon'],
                         coords=dict(time=xda.time.values,
                                     lat=xda.latitude.values,
                                     lon=xda.longitude.values))

    # creating time array
    year = xda_050m.time.to_index().year.unique().values[0]
    month = xda_050m.time.to_index().month.unique().values[0]
    ndays = monthlen(year, month)
    time = date_range(f'{year}-{month}-01', f'{year}-{month}-{ndays}')

    # interpolating data to quarter degree
    xda_025d = (
        xda_050m.interp(lat=arange(-89.875, 90, .25),
                        lon=arange(-179.875, 180, .25),
                        method='linear')
        # filling gaps due to interpolation along 180deg
        .roll(lon=720,
              roll_coords=False).interpolate_na(dim='lon', limit=10).roll(
                  lon=-720, roll_coords=False).reindex(time=time,
                                                       method='nearest'))

    return xda_025d.to_dataset(name='mxldepth')
Ejemplo n.º 18
0
async def download():
    tasks = list()
    sem = Semaphore(limit)

    async with ClientSession() as session:
        for pair in ['AUDUSD']:
            for year in [2014, 2015]:
                for month in range(1, 12):
                    for day in range(1, monthlen(year, month)):
                        for hour in range(0, 23):
                            tasks.append(
                                ensure_future(
                                    download_one(pair=pair,
                                                 year=str(year).zfill(2),
                                                 month=str(month).zfill(2),
                                                 day=str(day).zfill(2),
                                                 hour=str(hour).zfill(2),
                                                 session=session,
                                                 sem=sem)))
        return await gather(*tasks)
Ejemplo n.º 19
0
def number_of_days(year, month):
    '''
    Function will take the year and month and return the total number of days in
    that month.

    :param year: year wanted to be counted
    :param month: month which days are counted from
    :return: number of days in a given month
    '''

    # check year and month are type int
    assert type(year) == int
    assert type(month) == int

    # check month and year is within constraints
    assert month >= 1 and month <= 12
    assert year >= 0

    number_of_days = calendar.monthlen(year, month)

    return number_of_days
Ejemplo n.º 20
0
def plot_months(df, ax, title = 'Accidents per Day'):
    '''
        Prints a barchart of accidents per day in each month of the year
        
        ARGS:
            df - pandas df
            ax - axis to plot on

        Return:
            ax - axis with plot
    '''    
    df['year_mon'] = df['DATE'].apply(lambda x: (int(x.year), int(x.month)))
    df['weight'] = df['year_mon'].apply(lambda x: 1/cal.monthlen(x[0],x[1])/5)
    per_day = df.groupby(['month'])['weight'].sum()
    per_day

    sns.barplot(x = per_day.index, y = per_day, ax= ax, color = "firebrick")
    ax.set_ylim(65, 90)
    ax.set_title('Accidents by Month (Data averaged over 5 years)')
    ax.set_ylabel(title)
    name=filename(title)
    save_location='images/' + name + '.png'
    plt.savefig(save_location)
    return ax
Ejemplo n.º 21
0
 def get_len_of_month(cls, _datetime):
     return calendar.monthlen(_datetime.year, _datetime.month)
Ejemplo n.º 22
0
# isleap 判断某一年是否是闰年
isleap = calendar.isleap(2000)
print(isleap)
# leapdays: 获取指定年份之间的闰年的个数
nCount = calendar.leapdays(2001,2018)
print(nCount)
help(calendar.leapdays)

# month() 获取某个月的日历字符串
# 格式 calendar.month(年,月)
# 回值  月日历的字符串
cal3 = calendar.month(2018, 12)
print(cal3)

# 获取某年的某个月的天数
cal4 = calendar.monthlen(2018,12)

# monthrange()获取一个月的周几开始和天数
# 格式:calendar.monthrange(年,月)
# 返回值:元组(周几开始,总天数)
# 注意:周默认0~6,表示周一到周日

# help(calendar.monthrange(2018, 11))
w,t = calendar.monthrange(2018,11)
print(w)
print(t)

# monthcalendar() 返回一个月每天的矩阵列表
# 格式:calendar.monthcalendar(年,月)
# 返回值:二级列表
# 注意: 矩阵中没有天数用0表示
import calendar

print(calendar.monthrange(2019, 11))
print(calendar.monthlen(2019, 11))
Ejemplo n.º 24
0
def Calendar():
    aaa = calendar.monthlen(2020, 6)  # 月份多少天
    print(aaa)
Ejemplo n.º 25
0
    True
    True
    False
"""

print("##################### 3 #####################")
print(calendar.leapdays(2020, 2024))
print(calendar.leapdays(2020, 2025))
"""
output:
    1
    2
"""

print("##################### 4 #####################")
print("monthlen:", calendar.monthlen(2018, 10))
print("monthlen:", calendar.monthlen(2018, 11))
print("monthlen:", calendar.monthlen(2018, 12))
"""
output:
    monthlen: 31
    monthlen: 30
    monthlen: 31
"""

print("##################### 5 #####################")
print("prevmonth:", calendar.prevmonth(2018, 11))
print("nextmonth:", calendar.nextmonth(2018, 11))
"""
output:
    prevmonth: (2018, 10)
Ejemplo n.º 26
0
we will have import calender library
this library .or module includes several function we take a look  at few of them

'''
#import calender module
import calendar

date = input("enter the date(dd/mm/year): ")

day, month, year = date.split("/")

day = int(day)
month = int(month)
year = int(year)

#print("calender of month ", month, " of year ", year)
print(calendar.month(year, month))

print("month length: ", calendar.monthlen(year, month))

print("next month: ", calendar.nextmonth(year, month))

print("previous month: ", calendar.prevmonth(year, month))

print("week day(week start from monday):", calendar.weekday(year, month, day))
'''
let's have a look at few more basic functions

thank you for watching
'''
Ejemplo n.º 27
0
# @Author  : adair_chan
# @Email   : [email protected]
# @Date    : 2019/2/13 下午8:35
# @IDE     : PyCharm

import calendar

year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))

for i in range(1, month):
    """monthlen()函数计算某年份某个月有多少天"""
    day += calendar.monthlen(year, i)

print("it is the %dth day." % day)
Ejemplo n.º 28
0
    distperday= distperday/1000

    return(distperday)


fleetList = vehicleList(getFleetList(access_token,groupId))

#demander le mois

mois = int(input('Entrer le mois entre 1 et 12:'))


csvFields = ['vehicule','note','tags']
timeobj = ['vehicule']

for d in (date(2019, mois, i) for i in range(1, calendar.monthlen(2019, mois) + 1)):
    
    timeobj.append(d)
    csvFields.append(d.strftime("%A %d. %B %Y"))
    

    
#print(calendar.monthlen(2019, mois))


while True:
    try:
        jour = timeobj[1]
        ts =  time.mktime(jour.timetuple())
        start_ms = int(ts*1000)
        end_ms = start_ms+86399000
def run():
    print(f"二级部门{secApartmentIndex},编制{bianzhiIndex},入职时间{enterTimeIndex},离职时间{outTimeIndex}")
    try:
        print('---------------------时间计算----------------------------')
        # 获取到日历
        year = int(yearEntry.get())
        month = int(MonthEntry.get())

        cal = calendar.month(year, month)
        print(f"{year}年{month}月日历:")
        print(cal)
        # 计算当前月有多少天,用以获取最后一天的时间
        monthLen = calendar.monthlen(year, month)
        # 所以能计算出当前月的第一天,以及最后一天
        monthStartData = f"{year}/{month}/1"
        monthEndData = f"{year}/{month}/{monthLen}"
        # 将时间格式化成date格式
        monthStartData = datetime.strptime(monthStartData, '%Y/%m/%d')
        monthEndData = datetime.strptime(monthEndData, '%Y/%m/%d')

        # 获取所有的上班时间
        workDayAll = []
        # 获取当月的所有的上班日
        for i in range(1, monthLen + 1):
            day = f"{year}/{month}/{i}"
            day = datetime.strptime(day, '%Y/%m/%d')
            isWorkDay = chinese_calendar.is_workday(day)
            if isWorkDay:
                workDayAll.append(day)

        print(workDayAll)

        # 每周共有多少工作日
        workDays = len(workDayAll)
        # 每周的每人的工作总小时数,总工作日*8
        totalHourOnePersonMonth = workDays * 8

        print(f'当月开始时间:{monthStartData},当月结束时间:{monthEndData},当月需要工作天数:{workDays}')

        # 获取整行数据
        data_all = sheet.rows
        # 正编的小时数
        zhengbianTotalHour: int = 0
        # 外包的小时数
        waobaoTotalHour: int = 0
        # 符合要求的所有的人数
        totalPersonNum: int = 0

        # 元数组
        data_row = list(data_all)
        for row in data_row:
            # 获取二级部门,下标是1,编制在4,入职时间12,离职时间是13
            secDepartment: str = row[secApartmentIndex].value;
            # 姓名
            name: str = row[2].value
            # 编制
            bianzhi: str = row[bianzhiIndex].value
            # 入职时间
            enterTime: datetime = row[enterTimeIndex].value
            # 离职时间
            outTime: datetime = row[outTimeIndex].value

            # print(secDepartment)
            # 当不是这几个部门的时间,再开始计算这个人的当月的小时数
            if not '人事'.__eq__(secDepartment) and not '业务'.__eq__(secDepartment) and not '二级部门'.__eq__(
                    secDepartment) and secDepartment is not None:
                # 计算一下人数,也可以看到当前执行的位置
                totalPersonNum += 1
                # 输出当前行的所有数据
                # print(secDepartment, name, bianzhi, enterTime, outTime)
                if bianzhi.__eq__("正编"):  # 正编
                    # 当是在职状态下的时候,直接将在职改成下个月当天的时间。便于处理
                    if outTime.__str__().strip().__eq__("在职"):
                        outTime = monthEndData

                    if outTime >= monthEndData and enterTime < monthStartData:
                        # print(name, "离职时间是大于当月的,或者是月末最后一天,但是全勤")
                        zhengbianTotalHour += totalHourOnePersonMonth
                    else:
                        # 当月离职的。
                        if enterTime < monthStartData <= outTime < monthEndData:
                            print(name, "当月离职的", outTime)
                            for i in range(len(workDayAll)):
                                if outTime >= workDayAll[i]:
                                    # print(name, outTime, workDayAll[i])
                                    zhengbianTotalHour += 8
                        # 说明是当月就职的,并且当月不离职
                        elif monthStartData <= enterTime <= monthEndData < outTime:
                            # print(name, f"{month}月入职")
                            for i in range(len(workDayAll) - 1, 0, -1):
                                if enterTime <= workDayAll[i]:
                                    # print(name, enterTime, workDayAll[i])
                                    zhengbianTotalHour += 8
                        # 当月就职,当月离职
                        elif monthStartData <= enterTime <= monthEndData and outTime <= monthEndData:
                            # print(name, f"{month}月入职,当月离职了")
                            for i in range(len(workDayAll) - 1, 0, -1):
                                if enterTime <= workDayAll[i] <= outTime:
                                    # print(name, enterTime, workDayAll[i])
                                    zhengbianTotalHour += 8
                else:  # 外包
                    # 当是在职状态下的时候,直接将在职改成下个月当天的时间。便于处理
                    if outTime.__str__().strip().__eq__("在职"):
                        outTime = monthEndData

                    if outTime >= monthEndData and enterTime < monthStartData:
                        # print(name, "离职时间是大于当月的,或者是月末最后一天,但是全勤")
                        waobaoTotalHour += totalHourOnePersonMonth
                    else:
                        # 当月离职的。
                        if enterTime < monthStartData <= outTime < monthEndData:
                            # print(name, "当月离职的", outTime)
                            for i in range(len(workDayAll)):
                                if outTime >= workDayAll[i]:
                                    # print(name, outTime, workDayAll[i])
                                    waobaoTotalHour += 8
                        # 说明是当月就职的,并且当月不离职
                        elif monthStartData <= enterTime <= monthEndData < outTime:
                            # print(name, f"{month}月入职")
                            for i in range(len(workDayAll) - 1, 0, -1):
                                if enterTime <= workDayAll[i]:
                                    # print(name, enterTime, workDayAll[i])
                                    waobaoTotalHour += 8
                        # 当月就职,当月离职
                        elif monthStartData <= enterTime <= monthEndData and outTime <= monthEndData:
                            # print(name, f"{month}月入职,当月离职了")
                            for i in range(len(workDayAll) - 1, 0, -1):
                                if enterTime <= workDayAll[i] <= outTime:
                                    # print(name, enterTime, workDayAll[i])
                                    waobaoTotalHour += 8

        showinfo(message=f'去除人事以及业务总人数是{totalPersonNum}\n'
                         f'{month}月满勤共有{workDays}天上班时间,满勤总小时数是:{totalHourOnePersonMonth}\n'
                         f'{month}月正编工时数{zhengbianTotalHour}\n'
                         f'{month}月外包工时数{waobaoTotalHour}\n'
                         f'{month}月总工时数{waobaoTotalHour + zhengbianTotalHour}')
    except Exception:
        showinfo(message="运行出现了一点点问题,这里需要与0602sheet的格式保持一致")
Ejemplo n.º 30
0
def get_chart(current_spend, budget, as_of_date):
    current_day = as_of_date.day
    year = as_of_date.year
    days_in_month = calendar.monthlen(year, as_of_date.month)
    daily_budget = budget / days_in_month
    daily_burn = current_spend / current_day
    as_of = daily_budget * current_day
    days_away_from_budget = (as_of - current_spend) / daily_budget

    c = '#ff6666' if days_away_from_budget < 0 else '#95db96'
    daysAheadBehind = 'Behind' if days_away_from_budget < 0 else 'Ahead'

    fig = plt.figure(figsize=(6, 4), dpi=300)
    ax = plt.subplot2grid((3, 3), (0, 0), colspan=3)

    ax.barh(y=1, width=current_spend, color=c, zorder=2.5)
    ax.set_xlim(0, max(budget, current_spend) * 1.25)

    ax.vlines(budget, ax.get_ylim()[0], ax.get_ylim()[1], zorder=2.5)
    ax.vlines(as_of, ax.get_ylim()[0], ax.get_ylim()[1], ls='--', zorder=3.5)
    ax.text(current_spend - 200,
            1,
            '${:.0f}'.format(current_spend),
            rotation=-90,
            va='center',
            zorder=2.5)
    ax.text(budget + 1,
            1,
            '${:.0f}'.format(budget),
            rotation=-90,
            va='center',
            zorder=2.5)
    ax.set_title(chart_title(as_of_date))
    ax.get_yaxis().set_visible(False)
    ax.xaxis.set_ticks(np.arange(0, ax.get_xlim()[1], 250))
    ax.tick_params(axis='x', which='major', labelsize=8, rotation=45)
    ax.xaxis.grid(color='black',
                  linestyle='dotted',
                  linewidth=1,
                  alpha=.25,
                  zorder=.5)

    ax1 = plt.subplot2grid((3, 3), (1, 0))
    ax1.text(.5, .5, '${:.2f}'.format(daily_budget), ha='center', va='center')
    ax1.get_yaxis().set_visible(False)
    ax1.get_xaxis().set_visible(False)
    ax1.set_title('Daily Budget')

    ax2 = plt.subplot2grid((3, 3), (1, 1))
    ax2.text(.5, .5, '${:.2f}'.format(daily_burn), ha='center', va='center')
    ax2.get_yaxis().set_visible(False)
    ax2.get_xaxis().set_visible(False)
    ax2.set_title('Current Daily Spend')

    ax3 = plt.subplot2grid((3, 3), (1, 2))
    ax3.text(.5,
             .5,
             '{:.1f}'.format(days_away_from_budget),
             ha='center',
             va='center',
             color=c)
    ax3.get_yaxis().set_visible(False)
    ax3.get_xaxis().set_visible(False)
    ax3.set_title(f'Days {daysAheadBehind} of Budget')

    fig.tight_layout()
    return fig