コード例 #1
0
    def change_day(self, year, month):
        """最初に各ラベルを初期化"""
        self.clr_btn_txt()

        cl = Calendar(firstweekday=6)  # タプル(日付,曜日)が週毎に返される
        month_cl = cl.monthdays2calendar(year, month)
        i = 1  # "1"週目で初期化
        j = 0
        for week in month_cl:
            # weekは[1週目],[2週目],...
            for day in week:
                # dayは週毎の各日の(日付,曜日)
                if day[1] + 1 == 7: j = 0
                else: j = day[1] + 1

                if not day[0] == 0: self.set_btn_txt(i, j, str(day[0]))
            i += 1
コード例 #2
0
def get_month_days(year: int, month: int, start: int, end: int, every: int):
    days = Calendar().itermonthdays2(year, month)
    index = 0
    result = []
    for day in days:
        if day[0] != 0:
            result.append(day[0])
            index = index + 1
    try:
        if end < 0:
            end = len(result) + 1 + end
        if start < 0:
            start = len(result) + 1 + start
        return result[start - 1:end:every]
    except:
        pass
    return []
コード例 #3
0
 def get_table(self):
     calendar = Calendar(self.firstweekday).monthdatescalendar(
         self.year, self.month)
     starts, ends, oneday = self.get_contest_data(
         make_aware(datetime.combine(calendar[0][0], time.min)),
         make_aware(datetime.combine(calendar[-1][-1], time.min)))
     return [[
         ContestDay(
             date=date,
             weekday=self.weekday_classes[weekday],
             is_pad=date.month != self.month,
             is_today=date == self.today,
             starts=starts[date],
             ends=ends[date],
             oneday=oneday[date],
         ) for weekday, date in enumerate(week)
     ] for week in calendar]
コード例 #4
0
def getNumWeek():
    now = datetime.now()
    now_year = now.year

    if now.month > 6:
        first_month = 9
    else:
        first_month = 2
    sum_week = 0
    for i in range(first_month, now.month):
        sum_week += len(Calendar().monthdatescalendar(now_year, i))
    if sum_week % 2:
        num_week = 1
    else:
        num_week = 2

    return num_week
コード例 #5
0
def makeDateSetOfMonth(timeDate):
    #datetimeオブジェを引数としてうけとって生成します。
    OpeDay = timeDate
    cl = Calendar(firstweekday=0)
    list1 = list(cl.itermonthdates(OpeDay.year, OpeDay.month))
    list2 = []
    for elem in reversed(list1):
        if not elem.month == OpeDay.month:
            list1.remove(elem)

    days = ["(月)", "(火)", "(水)", "(木)", "(金)", "(土)", "(日)"]
    for elem in list1:
        list2.append(
            str(elem.month) + "月" + str(elem.day) + "日" + days[elem.weekday()])

    # print(list2)
    return list2
コード例 #6
0
def get_empty_year(leap=False):
    """Creates a list representing a year, elements represent days.
    
       Elements are lists formatted as [day, month, weekday], where
       weekdays are all set to be 0.
    """
    c = Calendar()
    l = list()
    if leap:
        year = 2020
    else:
        year = 2019
    for month in range(1, 13):
        for day in c.itermonthdays(year, month):
            if day != 0:
                l.append([day, month, 0])
    return l
コード例 #7
0
def get_week_wireframe(year, month, day):
    """
    Utility function for returning the current week
    """
    year, month, day = int(year), int(month), int(day)
    cal = Calendar()
    monthly_days = cal.monthdays2calendar(year, month)
    current_week = None
    for week in monthly_days:
        if [i for i, v in enumerate(week) if v[0] == day]:
            current_week = week
    return {
        'week': current_week,
        'year': year,
        'month': MONTHS[month],
        'today': day,
    }
コード例 #8
0
def calendar_page():
    calendar = Calendar()
    month = int(request.args.get("month"))
    year = int(request.args.get("year"))

    weeks = list(calendar.monthdays2calendar(year, month))
    
    while len(weeks) < 6:
        weeks.append([(0, i) for i in range(7)])

    data = {}
    data["weekdays"] = list(day_name)
    data["month"] = month
    data["month_name"] = month_name[month]
    data["year"] = str(year)

    return render_template("calendar.html", weeks=weeks, data=data)
コード例 #9
0
ファイル: database.py プロジェクト: kailashT/project
def create_query_for_month():
    try:
        sql_month_table = "CREATE TABLE IF NOT EXISTS " + datetime.date.today().strftime("%B%Y") + \
                          "( ID     integer NOT NULL"
        year = datetime.date.today().strftime("%Y")
        month_no = datetime.date.today().strftime("%m")
        month = Calendar().itermonthdates(int(year), int(month_no))
        for day in month:
            if day.month == int(month_no):
                sql_month_table = sql_month_table + ", '" + (
                    day.strftime("%y%m%d")) + "'"
                sql_month_table = sql_month_table + ("  text  NULL")
        sql_month_table = sql_month_table + ");"
        return sql_month_table
    except Exception as e:
        dlog.error(e)
        return False
コード例 #10
0
def createMonths(yr, birth, feier, bild):
    cal = Calendar(0)
    x, y = 0, 0
    drawString = "\\begin{figure}[!h]\n\\centering\n"
    if bild != "none":
        drawString += "\\tikz[overlay,remember picture]\\node[opacity=0.4]at (current page.center) {\includegraphics{" + bild + "}};"

    drawString += "\\begin{tikzpicture}[y=0.80pt, x=0.8pt,yscale=-1, inner sep=0pt,outer sep=0pt]"
    drawString += createYear(yr)
    for i in range(1, 13):
        x = x + 300
        y = 0
        drawString += "\n" + createRectangle(x, y, 0, i, dict(), dict(), 1)
        for ii in cal.itermonthdates(yr, i):
            drawString += "\n" + createRectangle(x, y, ii, i, birth, feier)
    drawString += "\end{tikzpicture}\n \n \end{figure}"
    return drawString
コード例 #11
0
def main():

    scheduler = Calendar()

    print(
        "Welcome to your appointment Scheduler! \n - To add a new appointment, enter add \n - To remove an existing appointment, enter remove \n - To view your scheduled appointments for a specific day, enter show day \n - To view all scheduled appointments for the week, enter show week \n - To exit the scheduler, enter exit"
    )
    func = input()
    while func != "exit":

        if func == "add":
            new = input(
                "Please enter the title of your appointment, the day, starting time and end time (HH:MM).\n"
            )
            title, day, start, end = new.split(" ")
            #within appointment we can check for valid time.

            newAppointment = Appointment(title.lower().capitalize(), start,
                                         end)

            scheduler.week[day.lower().capitalize()].add_appointment(
                newAppointment)
            #if new == "exit":
            #sys.exit(0)

        #do capitalize and lower for titles too.

        if func == "remove":
            remove = input(
                "Please enter the title, the day, starting and ending time of the appointment you wish to delete: (Example: Gym Monday 11:00 13:00)\n"
            )
            title, day, start, end = remove.split(" ")

            appointment = Appointment(title.lower().capitalize(), start, end)
            scheduler.week[day.lower().capitalize()].remove_appointment(
                appointment)

        if func == "show day":
            show_day = input("Please enter the day you wish to view.\n")
            print(scheduler.week[show_day.lower().capitalize()].__str__())

        if func == "show week":
            print(scheduler.__str__())

        func = input()
コード例 #12
0
ファイル: reports.py プロジェクト: joan2015/sentry
def to_calendar(interval, series):
    start, stop = get_calendar_range(interval, 3)

    legend, values = colorize(
        [
            "#fae5cf",
            "#f9ddc2",
            "#f9d6b6",
            "#f9cfaa",
            "#f8c79e",
            "#f8bf92",
            "#f8b786",
            "#f9a66d",
            "#f99d60",
            "#fa9453",
            "#fb8034",
            "#fc7520",
            "#f9600c",
            "#f75500",
        ],
        [value for timestamp, value in series if value is not None],
    )

    value_color_map = dict(values)
    value_color_map[None] = "#F2F2F2"

    series_value_map = dict(series)

    def get_data_for_date(date):
        dt = datetime(date.year, date.month, date.day, tzinfo=pytz.utc)
        ts = to_timestamp(dt)
        value = series_value_map.get(ts, None)
        return (dt, {"value": value, "color": value_color_map[value]})

    calendar = Calendar(6)
    sheets = []
    for year, month in map(index_to_month, range(start, stop + 1)):
        weeks = []

        for week in calendar.monthdatescalendar(year, month):
            weeks.append(map(get_data_for_date, week))

        sheets.append((datetime(year, month, 1, tzinfo=pytz.utc), weeks))

    return {"legend": list(legend.keys()), "sheets": sheets}
コード例 #13
0
ファイル: main.py プロジェクト: damoklov/common-algorithms
def main():
    calendar = Calendar()
    new_node = Node((5, 8))
    calendar.insert_into_sorted(new_node)
    new_node = Node((3, 5))
    calendar.insert_into_sorted(new_node)
    new_node = Node((0, 1))
    calendar.insert_into_sorted(new_node)
    new_node = Node((4, 8))
    calendar.insert_into_sorted(new_node)
    new_node = Node((10, 12))
    calendar.insert_into_sorted(new_node)
    new_node = Node((9, 12))
    calendar.insert_into_sorted(new_node)

    print(calendar)
    calendar.optimize()
    print(calendar)
コード例 #14
0
def find_next_boss_by_name(boss_name):
    boss = Boss[boss_name.upper()]
    now = datetime.utcnow() - timedelta(seconds=10800)  # -3 hours
    day = now.isoweekday()
    day_generator = Calendar(firstweekday=day).iterweekdays()

    schedule = week_schedule[day]
    for time, boss_list in schedule.items():
        if time.time > now.time() and boss in boss_list:
            return (boss_name, time, "hoje")
    next(day_generator)

    for week_day in day_generator:
        schedule = week_schedule[week_day]
        for time, boss_list in schedule.items():
            if boss in boss_list:
                return (boss_list, time, get_weekday_name(week_day))
    return ()
コード例 #15
0
def meetup(year, month, week, day_of_week):
    WEEK_GETTER = {
        "1st": lambda x: x[0],
        "2nd": lambda x: x[1],
        "3rd": lambda x: x[2],
        "4th": lambda x: x[3],
        "5th": lambda x: x[4] if len(x) == 5 else raise_(),
        "last": lambda x: x[-1],
        "teenth": lambda x: list(filter(lambda y: 13 <= y[2] < 20, x))[0],
    }
    cal = Calendar()
    month_cal = list(
        filter(
            lambda x: x[0] == year and x[1] == month and x[3] == WEEKDAY_NAMES[
                day_of_week],
            cal.itermonthdays4(year, month),
        ))
    return date(*WEEK_GETTER[week](month_cal)[:-1])
コード例 #16
0
def calendar(request, year=None, month=None):
    if year and month:
        date_object = date(int(year), int(month), 1)
    else:
        date_object = date.today()
    year, month = date_object.year, date_object.month
    events = Event.objects.filter(date__year=year, date__month=month)
    prev, next = get_prev_next(date_object)
    cal = Calendar().itermonthdates(date_object.year, date_object.month)
    return 'calendar.html', {
        'date': date_object,
        'prev': prev,
        'next': next,
        'days': DAYS,
        'cal': cal,
        'today': date.today(),
        'events': events
    }
コード例 #17
0
def meetup_day(year, month, day_name, day_specifier):
    weekday = day_names.index(day_name)
    days = [
        d.day for d in Calendar().itermonthdates(year, month)
        if d.month == month and d.weekday() == weekday
    ]

    if day_specifier in day_specifiers:
        try:
            idx = day_specifiers.index(day_specifier)
            return date(year, month, days[idx])
        except:
            raise MeetupDayException()
    elif day_specifier == 'last':
        return date(year, month, days[-1])
    elif day_specifier == 'teenth':
        day = [d for d in days if d > 12 and d < 20][0]
        return date(year, month, day)
コード例 #18
0
ファイル: models.py プロジェクト: karvox/pontox
    def horas_semana(self, ano, mes, semana):

        total = timedelta(hours=0, minutes=0)

        calendario = Calendar()
        listasemana = calendario.monthdays2calendar(year=ano, month=mes)

        try:
            for dia in listasemana[semana]:
                if not dia[0] == 0:
                    diatrabalhado = self.diatrabalho_set.filter(data=datetime(year=ano, month=mes, day=dia[0]))
                    if diatrabalhado:
                        diatrabalhado = diatrabalhado[0]
                        total += diatrabalhado.horas_trabalhadas()

            return total
        except IndexError:
            return timedelta(hours=0, minutes=0)
コード例 #19
0
def ns_form_validate(form):
    """
    :param form: form
    :return: template with all necessary data for new schedule or error message
    """
    workplace = form.workplace.data
    year = int(form.year.data)
    month = int(form.month.data)
    hours = form.hours.data
    month_name = MONTH_NAMES[month - 1]

    schedule_name = "%s-%s-%s" % (year, month, workplace)
    check_schedule = Schedule.query.filter_by(name=schedule_name).first()
    if check_schedule is not None:
        flash("Taki grafik już istnieje")
        return redirect(url_for("schedules.new_schedule"))

    workers_to_schd = []
    for worker in form.workers.data:
        workers_to_schd.append(str(worker).replace(" ", "_"))

    prev = prev_schedule(month, year, workplace)

    cal = Calendar()
    return render_template("schedules/empty_schedule.html",
                           title="Grafiki - nowy grafik",
                           workers=workers_to_schd,
                           shop=workplace,
                           year=year,
                           month=month,
                           mn=month_name,
                           cal=cal,
                           wdn=WEEKDAY_NAMES,
                           hours=hours,
                           Billing_period=Billing_period,
                           prev_shdict=prev["prev_shdict"],
                           prev_month=prev["month"],
                           prev_month_name=prev["month_name"],
                           prev_year=prev["year"],
                           prev_hours=prev["hours"],
                           prev_workers=prev["workers"],
                           workers_hours=prev["workers_hours"],
                           Shop=Shop,
                           Guidelines=Guidelines)
コード例 #20
0
ファイル: views.py プロジェクト: xuq/gnotty
def calendar(request, year=None, month=None, template="gnotty/calendar.html"):
    """
    Show calendar months for the given year/month.
    """

    try:
        year = int(year)
    except TypeError:
        year = datetime.now().year
    lookup = {"message_time__year": year}
    if month:
        lookup["message_time__month"] = month
    if hide_joins_and_leaves(request):
        lookup["join_or_leave"] = False

    messages = IRCMessage.objects.filter(**lookup)
    try:
        dates = messages.datetimes("message_time", "day")
    except AttributeError:
        dates = messages.dates("message_time", "day")
    days = [d.date() for d in dates]
    months = []

    if days:
        min_date, max_date = days[0], days[-1]
        days = set(days)
        calendar = Calendar(SUNDAY)
        for m in range(1, 13) if not month else [int(month)]:
            lt_max = m <= max_date.month or year < max_date.year
            gt_min = m >= min_date.month or year > min_date.year
            if lt_max and gt_min:
                weeks = calendar.monthdatescalendar(year, m)
                for w, week in enumerate(weeks):
                    for d, day in enumerate(week):
                        weeks[w][d] = {
                            "date": day,
                            "in_month": day.month == m,
                            "has_messages": day in days,
                        }
                months.append({"month": date(year, m, 1), "weeks": weeks})

    context = dict(settings)
    context["months"] = months
    return render(request, template, context)
コード例 #21
0
def list_book_for_month(year, month):
    """List all days for given month, and for each
    day list fact book entry.
    """
    data = asyncio.run(fetch_month_data(year, month))
    cal = Calendar()
    print("%12s | %12s | %12s | %12s" % ("day", "shares", "trades", "dollars"))
    print("%12s-+-%12s-+-%12s-+-%12s" %
          ("-" * 12, "-" * 12, "-" * 12, "-" * 12))

    for day in cal.itermonthdates(year, month):
        if day.month != month:
            continue
        if day in data:
            shares, trades, dollars = data[day]
        else:
            shares, trades, dollars = 0, 0, 0

        print("%12s | %12s | %12s | %12s" % (day, shares, trades, dollars))
コード例 #22
0
def makeDaysSetOfMonth(timeDate):
    OpeDay = timeDate
    cl = Calendar(firstweekday=0)
    list1 = list(cl.itermonthdates(OpeDay.year, OpeDay.month))
    for elem in reversed(list1):
        if not elem.month == OpeDay.month:
            list1.remove(elem)

    list2 = []
    for _, elem in enumerate(list1):

        if jpholiday.is_holiday(elem) or elem.weekday() >= 5:
            list2.append(1)
        else:
            list2.append(0)
        #休みの日なら1、そうでなければ0が入る

    # print(list2)
    return list2
コード例 #23
0
def guide_cal_profile(year):

    cal = Calendar(0)
    try:
        if not year:
            year = date.today().year
        cal_list = [
            cal.monthdatescalendar(year, i+1)
            for i in range(12)
        ]
        print(len(cal_list))
        for i in cal_list:
            print(len(i))
        print(cal_list[1][0])
    except:
        abort(404)
    else:
        return render_template('guide/cal_profile.html', year=year, cal=cal_list)
    abort(404)
コード例 #24
0
ファイル: plane.py プロジェクト: stolencatkarma/LDMUGM
    def __init__(self, name):
        # load file /planes/name.plane
        # players dont care about this unless
        # using a planar exit.
        self.name = name
        self.owners = list()  # list of characters who can act as admins
        self.calendar = Calendar(0, 0, 0, 0, 0, 0)
        self.rooms = list()
        self.room_map = dict()

        # i want a map that shows connected rooms
        # in a 3d view by room coordinates
        # connect by lines showing exits

        def parse_rooms(self):
            for room in self.rooms:
                # parse x,y,z
                # parse exits and planar exits
                pass
コード例 #25
0
ファイル: eventview.py プロジェクト: PandaPoPy/yolo
    def calendar(self):
        """
        Renders the view as a list of months.
        """
        if len(self.days) == 0:
            raise ValueError('Calendar rendering is not permitted without '
                             'events.')
        cal = Calendar()
        months = []
        remaining_days = sorted([k for k in self.days.keys()])
        current_day = remaining_days[0].replace(day=1)
        remaining_events = len(self.events)
        while remaining_events > 0:
            month = cal.monthdatescalendar(current_day.year, current_day.month)
            month_view = []
            for i, month_week in enumerate(month):
                month_view.append([])
                for j, day in enumerate(month_week):
                    if day.weekday() not in [5, 6]:  # weekend removal
                        month_view[i].append([])
                        if day in self.days:
                            events, daily_events_count = \
                                self._extract_day_events(day)
                            events = copy.deepcopy(events)
                            events.add_attributes({
                                'cur_month': day.month == current_day.month,
                            })
                            remaining_events -= daily_events_count
                            month_view[i][j] = events
                        else:

                            default_attributes = {
                                'active': False,
                                'today': day == date.today(),
                                'cur_month': day.month == current_day.month
                            }
                            month_view[i][j] = EventDay(
                                day,
                                attributes=default_attributes)
            months.append({'month': current_day,
                           'dates': month_view})
            current_day = current_day + relativedelta(months=1)
        return months
コード例 #26
0
ファイル: views.py プロジェクト: Razlagutt/med_registration
def get_datetime(args):

    # Блок получающий актуальные даты текущего месяца
    NOW = dt.today()
    dates = Calendar(0).itermonthdates(NOW.year, NOW.month)
    actual_dates = [
        date for date in dates
        if not (dt.isoweekday(date) in [6, 7]) and date >= NOW.date()
    ]

    WORK_DATES = []
    WORK_TIME = [time(hour, 0) for hour in range(9, 19)]
    for actual_date in actual_dates:
        for work_hour in WORK_TIME:
            WORK_DATES.append(dt.combine(actual_date, work_hour))

    # Извлекаем из queryset данные date, time. Не понимаю почему, но через for не хочет работать (хотя иногда работает),
    # требует целочисленный индекс у arg
    qs_dates = [
        dt.combine(dt.date(arg['pub_date']), dt.time(arg['pub_date']))
        for arg in args
    ]

    # Получаем список свободных дней и часов для записи к врачу
    [
        WORK_DATES.remove(work_date) for work_date in WORK_DATES
        if work_date in qs_dates
    ]

    # Сортируем список рабочих дат по возрастанию
    work_days = sorted({dt.date(work_date) for work_date in WORK_DATES})

    # Создаем словарь дата: [время] свободных для записи к врачу
    DATES_DICT = {}
    time_list = []
    for work_day in work_days:
        for work_date in WORK_DATES:
            if work_day == dt.date(work_date):
                time_list.append(dt.time(work_date).hour)
        DATES_DICT[work_day] = time_list
        time_list = []

    return {'work_dates': work_days, 'dates_dict': DATES_DICT}
コード例 #27
0
def meetup(year, month, week, day_of_week):
    days = [(y, m, d)
            for y, m, d, wd in Calendar().itermonthdays4(year, month)
            if m == month and day_name[wd] == day_of_week]
    if week == 'teenth':
        for y, m, d in days:
            if 10 < d < 20:
                day = date(y, m, d)
    elif week == 'last':
        day = date(days[-1][0], days[-1][1], days[-1][2])
    else:
        try:
            day_index = int(week[0]) - 1
            day = date(days[day_index][0], days[day_index][1],
                       days[day_index][2])
        except IndexError:
            raise MeetupDayException('Wrong date')

    return day
コード例 #28
0
def meetup_day(year, month, weekday, suffix):
    # compose list of date objects
    # only for the required days
    month_iter = Calendar().itermonthdates(year, month)
    days = [dt for dt in month_iter
            if  dt.strftime('%A') == weekday.capitalize() and \
                dt.month == month]

    if suffix == 'teenth':
        return next(dt for dt in days if dt.day >= 13)

    try:
        # get desired day number from string
        idx = int(suffix[0]) - 1
    except ValueError:
        # if fail, we are looking for 'last'
        idx = -1

    return days[idx]
コード例 #29
0
ファイル: models.py プロジェクト: 8area8/work-calendar
    def get_month(self,
                  from_now: int = 0,
                  until_last_of_week: bool = True) -> "DayManager":
        """Get a month."""
        month, year = self.set_month(from_now)
        monthdays: List[List[date]] = Calendar().monthdatescalendar(
            year, month)

        first_week = monthdays[0]
        last_week = monthdays[-1]

        start = first_week[0]
        if until_last_of_week:
            end = last_week[-1]
        else:
            day_number = monthrange(year, month)[-1]
            end = date(year, month, day_number)

        return self.filter(date__range=(start, end)).order_by("date")
def meetup_day(year, month, day_of_week, suffix):
    cal = Calendar(1)
    dayList = list(cal.itermonthdates(year, month))

    # Translate human numbers to real numbers
    dateDic = {
        '1st': 0,
        '2nd': 1,
        '3rd': 2,
        '4th': 3,
        'last': -1,
    }

    # Translate human days to numeric days
    dayDic = {
        'Monday': 0,
        'Tuesday': 1,
        'Wednesday': 2,
        'Thursday': 3,
        'Friday': 4,
        'Saturday': 5,
        'Sunday': 6,
    }
    # Our list of suspects
    possibleDays = []

    # Treat teenth specially(does anyone actually say that?)
    # I don't like this, it looks all ugly :(
    if suffix == 'teenth':
        for day in dayList:
            if day.day in range(13, 19) and \
            day.weekday() == dayDic[day_of_week]:
                meetupDay = day
    else:
        for day in dayList:
            # If it's the right day of the week and the right month, it's a suspect
            if day.weekday() == dayDic[day_of_week] and \
            day.month == month:
                possibleDays.append(day)
        meetupDay = possibleDays[dateDic[suffix]]

    return meetupDay