Example #1
0
    def events_source_in_week(self, request, pk, format=None):
        """
        Lista todos los eventos de la semana en la que nos encontramos
        :param request:
        :param pk:
        :param format:
        :return:
        """

        _pk = 0
        list_week = []
        list_events_week = []
        calendary = Calendar(0)
        today = timezone.localtime(timezone.now())
        year = today.year
        month = today.month
        events_in_week = 0

        if type(pk) is DictType:
            _pk = pk['pk']
            list_week = pk['list_week']
            month = pk['month']
            year = pk['year']
            events_in_week = pk['events_db']
        else:
            _pk = pk
            for it in calendary.monthdayscalendar(today.year, today.month):
                try:
                    if it.index(today.day):
                        list_week = it
                except ValueError:
                    pass

        if not events_in_week:
            try:
                events_in_week = Events.objects.filter(ID_Source=_pk)
            except Events.DoesNotExist:
                return HttpResponse(status=404)

        if request.method == 'GET':

            for it in list_week:
                if not it == 0:
                    dict_day = {'day': it, 'pk': _pk, 'year': year, 'month': month, 'events_db': events_in_week}
                    list_events_week.append(EventsInformation().events_source_in_day(request, dict_day))

            result = []  # Esta lista es para el uso interno de las otras funciones de la clase
            result_json = []  # Esta lista es para dar más información al json de la api
            count = 0
            for it in list_events_week:
                count += 1
                result_json.append({'day_week': count, 'events': it})
                for it_dict in it:
                    if it_dict:
                        result.append(it_dict)

            if type(pk) is DictType:
                return result
            else:
                return JSONResponse(result_json)
Example #2
0
    def render(self, context):
        mycal = Calendar()
        context[self.var_name] = mycal.monthdatescalendar(
            int(self.year.resolve(context)), int(self.month.resolve(context))
        )

        return ""
Example #3
0
def get_business_days_quantity(limit_day = 31):
    """
    Retorna quatidade de dias úteis no mês.
    """
    args = get_args()
    businessdays = 0
    calendar = Calendar()

    for week in calendar.monthdayscalendar(args.year, args.month):
        for i, day in enumerate(week):

            if day == 0 or i >= 5:
                continue

            for holiday in HOLIDAYS:
                if holiday['month'] == args.month and holiday['day'] == day:
                    businessdays -= 1
                    continue

            businessdays += 1

            if (int(day) == int(limit_day)):
                return businessdays

    return businessdays
Example #4
0
def get_last_day_of_month(year, month, day):
    month_list = Calendar().monthdatescalendar(year, month)
    month_list.reverse()
    for week in month_list:
        if week[day].month==month:
            return week[day]
    return None
Example #5
0
def get_week_count(firstdayofweek, firstweekofyear, year, month, day):
	cl = Calendar(firstdayofweek)
	data = cl.monthdayscalendar(year, 1)
	week_cnt = 0
	day_cnt = 0
	# counting for first month
	for i in range(0, 7):
		if data[0][i] != 0:
			day_cnt += 1
	if (firstweekofyear == 2 and day_cnt < 4) or (firstweekofyear == 3 and day_cnt < 7):
		week_cnt = -1
	if month != 1:		
		week_cnt += len(data)
		if data[len(data)-1][6] == 0:
			week_cnt -= 1
		#counting for other monthes
		for m in range(2, month):
			data = cl.monthdayscalendar(year, m)
			week_cnt += len(data)
			if data[len(data)-1][6] == 0:
				week_cnt -= 1
	#here we have week count in week_cnt before current month
	data = cl.monthdayscalendar(year, month)	
	for week in range(0, len(data)):
		week_cnt += 1
		if day in data[week]:
			break
	return week_cnt
Example #6
0
def show_month(tm):
    (ly, lm, ld) = get_lunar_date(tm)
    print
    print u"%d年%d月%d日" % (tm.year, tm.month, tm.day), week_str(tm), 
    print u"\t农历:", y_lunar(ly), m_lunar(lm), d_lunar(ld)
    print
    print u"日\t一\t二\t三\t四\t五\t六"

    c = Cal()
    ds = [d for d in c.itermonthdays(tm.year, tm.month)]
    count = 0
    for d in ds:
        count += 1
        if d == 0:
            print "\t",
            continue

        (ly, lm, ld) = get_lunar_date(datetime(tm.year, tm.month, d))
        if count % 7 == 0:
            print

        d_str = str(d)
        if d == tm.day:
            d_str = u"*" + d_str
        print d_str + d_lunar(ld) + u"\t",
    print
Example #7
0
    def render_month (self, x,y, month_no):
        svg = ''        
    
        svg += '<g>'
        svg += '<text x="%smm" y="%smm" font-family="\'%s\'" font-size="%smm" text-anchor="middle" fill="%s">'% (x + self.style['month-width']/2,y+self.style['month-padding-top'], self.style['month-font-family'], self.style['month-font-size'], self.style['month-color'])
        svg += '%s' % (self.month_names [month_no-1])
        svg += '</text>'
        svg += self.render_week (x, y+self.style['week-padding-top'])
        
        day_of_week = -1 # will start from Monday
        week_no = 0        

        c = Calendar (0)        
        for day_no in c.itermonthdays (self.year, month_no):

            day_of_week = (day_of_week + 1) % 7
            if day_of_week == 0: week_no += 1
            
            if day_no == 0: continue # month not yet started
            
            xx = x + self.style['day-width'] * (day_of_week)
            yy = y + self.style['day-padding-top'] + week_no * self.style['day-height']
            
            svg += self.render_day (xx, yy, month_no, day_no, day_of_week)
        
        svg += '</g>'
        return svg
Example #8
0
 def m_to_expiry(self, m_expiry):
     c = Calendar()
     expiry = datetime.strptime(m_expiry, '%Y%m%d')
     mdc = c.monthdatescalendar(expiry.year, expiry.month)
     fridays = [x[4] for x in mdc if x[4].month == expiry.month]
     if fridays[2] == expiry.date(): expiry += timedelta(days=1)        
     return expiry.strftime('%y%m%d')
Example #9
0
def meetup_day(year, month, name, ordinal):
    
    wkday_dict = {'Monday':0, 'Tuesday':1,
                  'Wednesday':2, 'Thursday':3,
                  'Friday':4, 'Saturday':5, 
                  'Sunday':6
                  }
    wkday = wkday_dict[name]
    
    cal = Calendar()
    date_list = []
    
    for day_date, weekday in cal.itermonthdays2(year, month):
        if weekday == wkday and not day_date == 0:
            date_list.append(day_date)
    
    date_dict = {'1st':0, '2nd':1, '3rd':2, '4th':3, '5th':4}
    if ordinal in date_dict:
        day = date_list[date_dict[ordinal]]
    elif ordinal == 'teenth':
        for day_date in date_list:
            if 12 < day_date < 20:
                day = day_date
    elif ordinal == 'last':
        day = date_list[-1]
                    
    
    return date(year, month, day)
    def _get_month_nth_weekday(self, in_date):
        """ Returns ZERO based nth date in month which weekday is the same
        as given (First monday, first sunday, second sunday etc...)

        @param in_date (date): random date in month
        @param weekday (int) : weekday index (0 --> Monday, ..., 6 --> Sunday)
        @param nth (int)     : number of weekday match (-1 --> Last, 0 --> First,...)
        """

        cal = Calendar(firstweekday=0)

        weekday = self._get_choosen_weekday()
        nth = self._get_choosen_weekday_position()

        month = in_date.month
        datelist = cal.itermonthdates(in_date.year, month)

        msg = 'nth ({}) param can not be less than -1 in _get_month_nth_weekday'
        assert nth >= -1, msg.format(nth)


        valid = [
            item for item in datelist \
            if item.weekday() == weekday and item.month == month
        ]

        return valid[nth] if len(valid) >= nth else None
Example #11
0
    def get_context_data(self, **kwargs):
        data = super(BaseCalendarMonthArchiveView, self).get_context_data(**kwargs)
        date = data['date_list'][0]
        
        cal = Calendar(self.get_first_of_week())

        month_calendar = []
        now = datetime.datetime.utcnow()
        
        date_lists = defaultdict(list)
        
        for obj in data['object_list']:
            obj_date = getattr(obj, self.get_date_field())            
            try:
                obj_date = obj_date.date()
            except AttributeError:
                # It's a date rather than datetime, so we use it as is
                pass                    
            date_lists[obj_date].append(obj)

        for week in cal.monthdatescalendar(date.year, date.month):
            week_calendar = []
            for day in week:
                week_calendar.append({
                    'day': day,
                    'object_list': date_lists[day],
                    'today': day == now.date(),
                    'is_current_month': day.month == date.month,
                })
            month_calendar.append(week_calendar)
            
        data['calendar'] = month_calendar

        return data
 def create_calendar_table(self):
     self.calendar_layout.clear_widgets()
     calendars = Calendar()
     calendars.setfirstweekday(calendar.SUNDAY)
     selected_month = self.month - 1
     year_dates = calendars.yeardays2calendar(year=self.year, width=1)
     th1 = KV.invoice_tr(0, 'Su')
     th2 = KV.invoice_tr(0, 'Mo')
     th3 = KV.invoice_tr(0, 'Tu')
     th4 = KV.invoice_tr(0, 'We')
     th5 = KV.invoice_tr(0, 'Th')
     th6 = KV.invoice_tr(0, 'Fr')
     th7 = KV.invoice_tr(0, 'Sa')
     self.calendar_layout.add_widget(Builder.load_string(th1))
     self.calendar_layout.add_widget(Builder.load_string(th2))
     self.calendar_layout.add_widget(Builder.load_string(th3))
     self.calendar_layout.add_widget(Builder.load_string(th4))
     self.calendar_layout.add_widget(Builder.load_string(th5))
     self.calendar_layout.add_widget(Builder.load_string(th6))
     self.calendar_layout.add_widget(Builder.load_string(th7))
     if year_dates[selected_month]:
         for month in year_dates[selected_month]:
             for week in month:
                 for day in week:
                     if day[0] > 0:
                         item = Factory.CalendarButton(text="[b]{}[/b]".format(day[0]))
                     else:
                         item = Factory.CalendarButton(disabled=True)
                     self.calendar_layout.add_widget(item)
Example #13
0
def get_month_events(year, month):
    # Get the day-dates of the current month
    cal = Calendar(0) # default replace by user db? (starting day)
    the_month = cal.monthdatescalendar(year, month)

    # First day of first week
    begin = the_month[0][0]
    # Last day of last week
    end = the_month[-1][-1]
    events = Event.query.filter(
        Event.event_date > begin.strftime('%Y-%m-%d'),
        Event.event_date < end.strftime('%Y-%m-%d')) \
        .options(lazyload('creator')).all()

    # Load the days for the calendar
    def per_day(day):
        # Get the interval bounds of that day
        day_start = datetime.combine(day, time())
        day_end = day_start + timedelta(days = 1)
        # Run through all events
        day_events = []
        for e in events:
            if e.event_date >= day_start and e.event_date < day_end:
                day_events.append(e)
        return (day, day_events)
    def per_week(week):
        return [per_day(d) for d in week]
    def per_month(month):
        return [per_week(w) for w in month]

    return per_month(the_month)
Example #14
0
	def month_sales(self,farm):
		'''This function returns the monthly sales'''
		date = datetime.date.today()
		cal = Calendar()
		days_month=list(set(list(cal.itermonthdays(date.year, date.month)))-set([0]))
		orders = PurchaseOrder.objects.filter(farm=farm,date__month=date.month,date__year=date.year)
		products=PurchaseOrder.objects.product_order_month(farm,date)
		total_day=[]
		count_sales=[]
		for day in days_month:
			total_day.append(0)
			count_sales.append(0)
		total_month=0
		total_products = PurchaseOrder.objects.count_products_month(farm,date)
		for order in orders:
			for idx,day in enumerate(days_month):
				if order.date.day==day:
					total = order.total_order
					t_products = order.quantity
					if total_day[idx]!=0:
						price  = total_day[idx]+total
						total_day[idx]=price
						total_month+=total
						count = count_sales[idx]
						count_sales[idx]=(count+t_products)
					else:
						total_month+=total
						total_day[idx]=total
						count_sales[idx]=(t_products)

					break
		data = {'labels':days_month, 'values':total_day, 'count':count_sales, 'total_month':total_month, 'total_products':total_products, 'products':products}
		return data
Example #15
0
	def week_sales(self,farm):
		'''This function returns the weekly deals'''
		date = datetime.date.today()
		orders = PurchaseOrder.objects.order_week(farm=farm,date=date)
		products_order=PurchaseOrder.objects.product_order_week(farm=farm,orders=orders)
		total_products = products_order[0]['total']
		products = products_order[1]
		sales_day=[]
		count_sales=[]
		total_day=0
		cal = Calendar()
		days = list(cal.iterweekdays())
		for day in days:
			sales_day.append(0)
			count_sales.append(0)
		for order in orders:
			order_day=order.date.isocalendar()[2]
			total = order.total_order
			t_products = order.quantity
			for day in days:
				if day==order_day:
					if sales_day[day]!=0:
						price  = sales_day[day]+total
						sales_day[day]=price
						total_day+=total
						count = count_sales[day]
						count_sales[day]=(count+t_products)
					else:
						total_day+=total
						sales_day[day]=total_day
						count_sales[day]=(t_products)
					break
		data = {'values':sales_day, 'count':count_sales, 'total_day':total_day, 'total_products':total_products, 'products':products}
		return data
Example #16
0
def generate_random():
    'Generates a years worth of random logs.'

    p = path('c:\\test')

    words = 'foo bar to be or not the and apple orange banana cherry futon proleptic gregorian ordinal'.split()

    cal = Calendar()

    for month in xrange(1, 12):
        for day in cal.itermonthdates(2007, month):

            messages = []
            for x in xrange(2, randrange(20, 50)):
                shuffle(words)

                messages.append(
                    S(buddy     = S(name = 'digsby0%d' % randrange(1, 3)),
                      timestamp = random_time_in_day(day),
                      message   = ' '.join(words[:randrange(1, len(words)+1)])))

            messages.sort(key = lambda mobj: mobj['timestamp'])

            daylog = p / (day.isoformat() + '.html')

            with daylog.open('w') as f:
                f.write(html_header % dict(title = 'IM Logs with %s on %s' % ('digsby0%d' % randrange(1, 3), day.isoformat())))

                for mobj in messages:
                    f.write(generate_output_html(mobj))
Example #17
0
def sick(request,user_id):
    users = User.objects.all()
    selected = User.objects.get(pk=user_id)
    user_days = Day.objects.filter_user(user_id)

    year_form = YearChangeForm({'year':request.session.get('year',2013)})
    year = int(request.session.get('year',2013))

    cal = MikranCalendar(user_days,year)

    if request.method == 'POST': # If the form has been submitted...
        form = SickForm(user=request.user, data=dict(request.POST.items() + {'user_id':selected.id}.items())) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            start_date = datetime.date(int(request.POST['first_day_year']),
                                       int(request.POST['first_day_month']),
                                       int(request.POST['first_day_day']))
            
            end_date = datetime.date(int(request.POST['last_day_year']),
                                     int(request.POST['last_day_month']),
                                     int(request.POST['last_day_day']))

            start_month = int(request.POST['first_day_month'])
            end_month = int(request.POST['last_day_month'])

            status_obj = Status.objects.get(status=form.translateChoice(request.POST['status']));

            days = []
            current = Calendar()
            for month in range(start_month,end_month+1):
                for day in current.itermonthdates(int(request.POST['first_day_year']),month):
                    if day >= start_date and day <= end_date:
                        if day.isoweekday() < 6:
                            if not day in days:
                                if not day.strftime("%02d-%02m-%04Y") in cal.get_free_days(year):
                                    days.append(day)

            #build list of objects for bulk create
            Day.objects.bulk_create([Day(user_id=selected.id,status_id=status_obj.id,leave_date=day) for day in days])
            #send bulk sick days create signal
            days_planned.send(sender=User, user=selected, status=status_obj, start=start_date, end=end_date, operation="SICK".encode('utf-8'))

            #display OK message for the user
            messages.add_message(request,messages.INFO, 'Zgłosiłeś zwolnienie lekarskie od %s do %s' %(start_date,end_date))

            return HttpResponseRedirect(reverse('leave.views.show_user',args=(selected.id,)))
    else:
        form = SickForm()
        
    return render_to_response('sick_days.html',{'users': users,
                                                'selected':selected,
                                                'user_days':user_days,
                                                'cal':mark_safe(cal.formatyear(year,4)),
                                                'year_form':year_form,
                                                'days_present': user_days.filter_present().count(),
                                                'days_sick':user_days.filter_sick().count(),
                                                'days_planned':user_days.filter_planned().count(),
                                                'days_accepted':user_days.filter_accepted().count(),
                                                'form':form},
                              context_instance=RequestContext(request))
Example #18
0
def calc_month_leave_accnt(db, empid, month=datetime.date.today().month, year=datetime.date.today().year):
  leaves = get_leaves(db, empid, month, year)
  cal = Calendar()
  working_days = [w for w in cal.iterweekdays()]
  total_working_days = len(working_days) + len(get_working_days(db)) - len(get_holidays(db))
  total_leaves = (0, len(leaves) - 2)[len(leaves) > 2]
  total_pay_days = total_working_days - total_leaves
  return {'working_days':total_working_days, 'total_leaves':total_leaves}
Example #19
0
def index(year):
	cal = Calendar(0)
	try:
		if not year:
			year = date.today().year
		cal_list = [cal.monthdatescalendar(year, i+1) for i in xrange(12)]
	except Exception, e:
		abort(404)
Example #20
0
def _calendar(selected_date, selected_place):
    place = selected_place
    year, month = selected_date.year, selected_date.month
    filters = {'date__year':  year, 'date__month': month, 'place': place}
    bookings = {b.date: b for b in Booking.objects.filter(**filters)}
    calendar = Calendar(firstweekday=6)
    for week in calendar.monthdatescalendar(year, month):
        yield [(day, bookings.get(day)) for day in week]
Example #21
0
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,
    }
Example #22
0
def list_sessions(request, year=None, month=None):
    args = {}

    today = date.today()

    if year is None:
        year = today.year
        month = today.month
    else:
        year = int(year)
        month = int(month)

    current = date(year, month, 1)
    nextmonth = current + relativedelta(months=1)
    prevmonth = current - relativedelta(months=1)

    args["year"] = year
    args["month"] = month
    args["current"] = current
    args["prevmonth"] = prevmonth
    args["nextmonth"] = nextmonth

    cal = Calendar()
    days = cal.monthdatescalendar(year, month)

    q = Q(nr_votes__gt=0) | Q(nr_statements__gt=0)
    date_q = Q(plsess__date__gte=current, plsess__date__lte=nextmonth)
    pl_items = PlenarySessionItem.objects.filter(q & date_q).select_related('plsess').order_by('plsess__date')

    acc = {}

    for pl_item in pl_items:
        statements, votes, plsess = acc.setdefault(pl_item.plsess.date, (0, 0, None))

        statements += pl_item.nr_statements
        votes += pl_item.nr_votes
        plsess = pl_item.plsess.url_name

        acc[pl_item.plsess.date] = statements, votes, plsess

    def _date_to_info(d):
        info = {}
        info['date'] = d
        info['weekdayclass'] = "small" if d.weekday() in [5, 6] else "normal"
        info['today'] = d == today
        info['offmonth'] = d.month != current.month or d.year != current.year

        statements, votes, plsess = acc.setdefault(d, (0, 0, None))
        info["statements"] = statements
        info["votes"] = votes
        info["plsess"] = plsess

        return info

    args["weeks"] = map(lambda w: map(_date_to_info, w), days)

    return render_to_response('new_sessions.html', args, context_instance=RequestContext(request))
Example #23
0
def get_month(y, m):
    """ 
    Return list of month's weeks, which day 
    is a turple (<month day number>, <weekday number>) 
    """
    
    cal = Calendar()
    month = cal.monthdays2calendar(y, m)
    
    # Add additional num to every day which mark from 
    # this or from other day that day numer
    for week in range(len(month)):
        for day in range(len(month[week])):
            _day = month[week][day]
            if _day[0] == 0:
                this = 0
            else: 
                this = 1
            _day = (_day[0], _day[1], this)
            month[week][day] = _day
    
    # Days numbers of days from preious and next monthes
    # marked as 0 (zero), replace it with correct numbers
    # If month include 4 weeks it hasn't any zero
    if len(month) == 4:
        return month        
    
    quater = calc_quarter(y, m)
    
    # Zeros in first week    
    fcount = 0
    for i in month[0]:
        if i[0] == 0:
            fcount += 1
    
    # Zeros in last week
    lcount = 0
    for i in month[-1]:
        if i[0] == 0:
            lcount += 1
            
    if fcount:
        # Last day of prev month
        n = monthrange(quater[0][0], quater[0][1])[1]
        
        for i in range(fcount):
            month[0][i] = (n - (fcount - 1 - i), i, 0)
            
    if lcount:
        # First day of next month
        n = 1
        
        for i in range(lcount):
            month[-1][-lcount + i] = (n + i, 7 - lcount + i, 0)
            
    return month
Example #24
0
def index(year):
	conn = pymongo.MongoClient()
	db = conn.test
	cal = Calendar(0)
	try:
		if not year:
			year = date.today().year
		cal_list = [cal.monthdatescalendar(year, i+1) for i in xrange(12)]	
	except Exception, e:
		abort(404)
Example #25
0
def calendarSite(year, month):
   
   cal = Calendar()

   weeks = cal.monthdayscalendar(year = year, month = month)
   for week in weeks:
      for i in range(0, len(week)):
         if week[i] == 0:
            week[i] = ""
   return {'year': year, 'month': months[month-1] ,'dayNames' : dayNames, 'weeks' : weeks}
def find_mondays(year, month):
    cal = Calendar()
    mondays = list()
    for week in cal.monthdays2calendar(year, month):
        for day in week:
            (monthday, weekday) = day
            if (weekday == 1 and monthday > 0):
                mondays.append(datetime.date(year=year,
                                             month=month,
                                             day=monthday))
    return mondays
Example #27
0
def week_calendar(days):
    cal = Calendar(6)
    today = date.today() + timedelta(days=days)
    weeks = cal.monthdatescalendar(today.year, today.month)
    current_week = []
    for week in weeks:
        if week[0] <= today <= week[6]:
            current_week = week
            break

    return current_week
Example #28
0
    def get_context_data(self, **kwargs):

        def get_weekday_text(athlete, weekday):
            morph = pymorphy2.MorphAnalyzer()
            if athlete.week_day:
                for week_day in eval(athlete.week_day):
                    if weekday < int(week_day):
                        day_text = morph.parse(Athlete.WEEK_DAYS[int(week_day)][1])[0].inflect({'accs'}).word
                        return 'во' if Athlete.WEEK_DAYS[int(week_day)][0] == 1 else 'в', day_text
                day_text = morph.parse(Athlete.WEEK_DAYS[int(eval(athlete.week_day)[0])][1])[0].inflect({'accs'}).word
                return 'во' if Athlete.WEEK_DAYS[int(eval(athlete.week_day)[0])][0] == 1 else 'в', day_text
            return 'не', 'запланирована'

        athlete = Athlete.objects.get_or_create(user=self.request.user)[0]
        today = datetime.now().date()
        cal = Calendar(MONDAY)
        year = int(self.kwargs.get('year'))
        month = int(self.kwargs.get('month'))
        day = int(self.kwargs.get('day'))
        current_date = date(year, month, day)
        next_month = add_months(current_date, 1)
        prev_month = sub_months(current_date, 1)
        month_dates = list(cal.itermonthdates(year, month))
        trainings = Training.objects.filter(
            date__in=month_dates,
            workout_diary=self.object
        )
        month_dates_with_training = [
            (item, True) if athlete.week_day and item >= today
            and str(item.weekday()) in athlete.week_day
            else (item, trainings.filter(date=item).last())
            for item in month_dates
        ]
        splited = chunks(month_dates_with_training, 7)
        month = [(week[0][0].isocalendar()[1] == today.isocalendar()[1], week) for week in splited]
        training_today = athlete.week_day and (str(today.weekday()) in athlete.week_day)
        training = get_training(self.request.user, current_date)
        ctx = {
            'training': training,
            'today': today,
            'month': month,
            'prev_month': prev_month,
            'next_month': next_month,
            'current_month': month_text(current_date.month),
            'current_date': current_date,
            'current_weekday': Athlete.WEEK_DAYS[current_date.weekday()][1],
            'training_duration': athlete.get_training_duration_display(),
            'history': current_date < today,
            'training_today': training_today,
            'button_text': (True, 'Начать тренировку')
            if training_today else
            (False, 'Следующая тренировка %s %s' % get_weekday_text(athlete=athlete, weekday=today.weekday()))
        }
        return ctx
Example #29
0
def calendar(tasks, date_obj=date.today()):
    month, year = date_obj.month, date_obj.year
    tasks = tasks

    dates = Calendar()
    weeks = [process_week(week, month, year) for week in
             dates.monthdays2calendar(year, month)]
    weeks = [check_tasks(week, tasks) for week in weeks]
    return {
        'weeks': weeks,
        'date_obj': date_obj,
    }
Example #30
0
def main():
  root = Tk()
  root.title("Money Timer")
  root.lift()
  cf = ClockFace(root, size = 100, smooth = True, bg = PhotoImage(file = "art.gif"), handcolor = "#000000", markcolor = "#000000")
  cf.grid(row = 0, column = 0)
  mt = MoneyTimer(root)
  mt.grid(row = 0, column = 1)
  cal = Calendar(root)
  cal.grid(row = 1, column = 0, columnspan = 2)

  root.mainloop()
from datetime import datetime

from calendar import Calendar
from event import Event

calendar = Calendar()

calendar.add_event(
    Event("Revise the Open Closed principle",
          start=datetime(2020, 9, 19, 11),
          end=datetime(2020, 9, 19, 13, 30),
          attendees=['George Eeliot']))

calendar.add_event(
    Event("Skiller Whale Session",
          start=datetime(2020, 9, 20, 15),
          end=datetime(2020, 9, 20, 16),
          attendees=["Salmon Rushdie"]))

calendar.add_event(
    Event("Learn about Orca Culture",
          start=datetime(2020, 9, 20, 16),
          end=datetime(2020, 9, 20, 18, 30)))

# TODO: Define a subclass of Event called Meeting, which has a `location` attribute
...

# calendar.add_event(
#     Meeting("Important Discussions",
#             start=datetime(2020, 9, 21, 17, 0),
#             end=datetime(2020, 9, 21, 17, 45, 0),
Example #32
0
    def render(self, context):
        mycal = Calendar()
        context[self.var_name] = mycal.monthdatescalendar(
            int(self.year.resolve(context)), int(self.month.resolve(context)))

        return ''
    def get(self):
        if self.request.user is not None:
            now = datetime.now()
            if 0 <= now.hour < 12:
                day_for_new_plan = date.today()
                day_for_evaluate_plan = date.today() - timedelta(days=1)
            elif 21 <= now.hour <= 24:
                day_for_new_plan = date.today() + timedelta(days=1)
                day_for_evaluate_plan = date.today()
            else:
                day_for_new_plan = None
                day_for_evaluate_plan = None

            if day_for_new_plan is not None:
                list_of_new_plan = DBSession.query(PlanList).filter(
                    PlanList.user == self.request.user,
                    PlanList.date == day_for_new_plan,
                ).first()
                if list_of_new_plan is None:
                    list_of_new_plan = PlanList(self.request.user,
                                                day_for_new_plan)
                    DBSession.add(list_of_new_plan)
            else:
                list_of_new_plan = None

            if day_for_evaluate_plan is not None:
                list_of_evaluate_plan = DBSession.query(PlanList).filter(
                    PlanList.user == self.request.user,
                    PlanList.date == day_for_evaluate_plan,
                ).first()
                if list_of_evaluate_plan is None:
                    list_of_evaluate_plan = PlanList(self.request.user,
                                                     day_for_evaluate_plan)
                    DBSession.add(list_of_evaluate_plan)
            else:
                list_of_new_plan = None

            if u'cal' in self.request.GET:
                match = re.match(r'^([0-9]{4})-([01][0-9])$',
                                 self.request.GET.get(u'cal', u''))
                if match:
                    year, month = int(match.group(1)), int(match.group(2))
                else:
                    today = date.today()
                    year, month = today.year, today.month
            else:
                today = date.today()
                year, month = today.year, today.month
            calendar = (
                date(year, month, 1),
                Calendar(6).monthdatescalendar(year, month),
                date(year, month,
                     monthrange(year, month)[1]),
            )

            now = datetime.now()
            if 0 <= now.hour < 12:
                today_on_history = date.today() - timedelta(days=1)
            else:
                today_on_history = date.today()

            return {
                'day_for_new_plan': day_for_new_plan,
                'list_of_new_plan': list_of_new_plan,
                'day_for_evaluate_plan': day_for_evaluate_plan,
                'list_of_evaluate_plan': list_of_evaluate_plan,
                'add_plan_form':
                self.plan_form.render({'date': day_for_new_plan}),
                'calendar': calendar,
                'today_on_history': today_on_history,
            }
        return {}
Example #34
0
def process_xml():
    try:
        server_path = os.path.join(directories["xml_root"], "server.xml")
        server_xml = ElementTree.parse(server_path).getroot()
    except:
        log("FATAL",
            "Unable to open and parse server.xml: %s" % server_path,
            exit_code=1)

    w = World()

    for option in server_xml.findall('option'):
        name = required_attribute(option, 'name')
        value = required_attribute(option, 'value')
        if not options.has_key(name):
            log("FATAL",
                "<option> tag sets unknown option %s" % name,
                exit_code=1)
        options[name] = value
        log("CONFIG", "Option [%s] set to '%s'" % (name, value))
        server_xml.remove(option)

    for s in server_xml.findall('stance'):
        file = required_attribute(s, 'file')
        log("STANCE", "Processing stances at %s" % file)
        try:
            stance_path = os.path.join(directories["xml_root"], file)
            stance_xml = ElementTree.parse(stance_path).getroot()
        except:
            log("FATAL", "Unable to parse stance file", exit_code=1)
        process_stance(stance_xml)
        server_xml.remove(s)

    for area in server_xml.findall('area'):
        file = required_attribute(area, 'file')
        name = required_attribute(area, 'name')
        log("AREA", "Processing area [%s] at %s" % (name, file))
        try:
            area_path = os.path.join(directories["xml_root"], file)
            area_xml = ElementTree.parse(area_path).getroot()
        except:
            log("FATAL", "Unable to parse area file", exit_code=1)
        process_area(area_xml, name)
        server_xml.remove(area)

    for calendar in server_xml.findall('calendar'):
        file = required_attribute(calendar, 'file')
        name = required_attribute(calendar, 'name')
        log("CALENDAR", "Processing calendar [%s] at %s" % (name, file))
        try:
            calendar_path = os.path.join(directories["xml_root"], file)
            calendar_xml = ElementTree.parse(calendar_path).getroot()
        except:
            log("FATAL", "Unable to parse calendar file", exit_code=1)

        w.calendars.append(Calendar(calendar_xml, name))
        server_xml.remove(calendar)

    for handlers in server_xml.findall('handlers'):
        file = required_attribute(handlers, 'file')
        log("HANDLERS", "Processing handlers mapping at %s" % file)
        try:
            handlers_path = os.path.join(directories["xml_root"], file)
            handlers_xml = ElementTree.parse(handlers_path).getroot()
        except:
            log("FATAL", "Unable to parse handler mapping", exit_code=1)
        process_handlers(handlers_xml)
        server_xml.remove(handlers)

    for child in server_xml.getchildren():
        log("ERROR",
            "Ignoring unknown tag <%s> in server.xml" % child.tag,
            problem=True)
Example #35
0
    def _populate(self, year):
        # New Year's Day
        name = "New Year's Day"
        self[date(year, 1, 1)] = name

        # Birthday of Prophet, Mawlid in India
        # 12th day of 3rd Islamic month
        name = "Birth of Prophet"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 11, 20)[0]
            y, m, d = to_gregorian(islam_year, 3, 12)
            if y == year:
                self[date(y, m, d)] = name

        # Chinese New Year
        name = "Chinese New Year"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 1, 1)).to_date()
            if ds.year == year:
                self[ds] = name

        # Tamil New Year
        # Note: it's not necessarily 04/14
        # due to the local calendar
        # other possible dates are 04/13 and 04/15
        name = "Tamil New Year"
        self[date(year, 4, 14)] = name

        # Good Friday
        name = "Good Friday"
        for offset in range(-1, 2, 1):
            ds = easter(year + offset) - rd(days=2)
            if ds.year == year:
                self[ds] = name

        # Labor Day
        name = "Labor Day"
        self[date(year, 5, 1)] = name

        # Buddha's Birthday
        name = "Wesak Day"
        for offset in range(-1, 2, 1):
            ds = Converter.Lunar2Solar(Lunar(year + offset, 4, 15)).to_date()
            if ds.year == year:
                self[ds] = name

        # King's birthday
        # https://www.thestar.com.my/news/nation/2017/04/26/
        # Before 2017: first Saturday of June
        # 2017-2021: last Saturday of July
        name = "King's birthday"
        if year < 2017:
            c = Calendar(firstweekday=MONDAY)
            monthcal = c.monthdatescalendar(year, 6)

            l1 = len(monthcal)
            saturdays = []
            for i in range(l1):
                if monthcal[i][5].month == 6:
                    saturdays.append(monthcal[i][5])
            self[saturdays[0]] = name
        elif (year >= 2017) and (year <= 2021):
            c = Calendar(firstweekday=MONDAY)
            monthcal = c.monthdatescalendar(year, 7)

            l1 = len(monthcal)
            saturdays = []
            for i in range(l1):
                if monthcal[i][5].month == 7:
                    saturdays.append(monthcal[i][5])
            self[saturdays[-1]] = name

        # Eid al-Fitr
        name = "Eid al-Fitr"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 6, 15)[0]
            y1, m1, d1 = to_gregorian(islam_year, 10, 1)
            y2, m2, d2 = to_gregorian(islam_year, 10, 2)
            if y1 == year:
                self[date(y1, m1, d1)] = name
            if y2 == year:
                self[date(y2, m2, d2)] = name

        # Malaysia Day
        name = "Malaysia Day"
        self[date(year, 9, 16)] = name

        # Feast of the Sacrifice
        name = "Feast of the Sacrifice"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 8, 22)[0]
            y, m, d = to_gregorian(islam_year, 12, 10)
            if y == year:
                self[date(y, m, d)] = name

        # First Day of Muharram
        name = "First Day of Muharram"
        for offset in range(-1, 2, 1):
            islam_year = from_gregorian(year + offset, 9, 11)[0]
            y, m, d = to_gregorian(islam_year + 1, 1, 1)
            if y == year:
                self[date(y, m, d)] = name

        # Christmas
        name = "Christmas Day"
        self[date(year, 12, 25)] = name
Example #36
0
from calendar import Calendar
print(Calendar().monthdays2calendar(2000, 4))
Example #37
0
 def __init__(self, **kwargs):
     Calendar.__init__(self)
     self.locale = check_locale(kwargs['locale']) if 'locale' in kwargs else DEFAULT_LOCALE
     self.non_work_days, self.work_days = get_prodcals(self.locale)
     self.time_per_day = kwargs['tm_day'] if 'tm_day' in kwargs else DEFAULT_TIME_PER_DAY
Example #38
0
    def fetch_ohlcv(self,
                    code: str,
                    timeframe: tuple,
                    since: datetime,
                    limit: int,
                    fill_gap=False,
                    use_adjusted_price=True) -> List[Candle]:
        """
        https://money2.creontrade.com/e5/mboard/ptype_basic/HTS_Plus_Helper/DW_Basic_Read_Page.aspx?boardseq=288&seq=102&page=2&searchString=&p=&v=&m=

        :param code: 종목 코드
        :param timeframe:
        :param since:
        :param limit:
        :param fill_gap: 갭보정 여부
        :param use_adjusted_price: 수정주가 사용여부
        :return:
        """
        if limit > 2856:
            raise ValueError(
                "Too big request, increase period_unit or reduce date range")

        timeframe_timedelta = timeframe_to_timedelta(timeframe)
        if timeframe[1] == TimeFrameUnit.DAY:
            to = since + (timeframe_timedelta * limit) - timedelta(minutes=1)
            # 23시 59분으로 만들기 위해
        else:
            to = since + (timeframe_timedelta * limit)

        if timeframe[1] in [TimeFrameUnit.MINUTE, TimeFrameUnit.TICK]:
            market_end = datetime(since.year, since.month, since.day, 15, 21,
                                  0)
            diff: timedelta = market_end - since
            count = int(diff.total_seconds()) // timeframe_timedelta.seconds
            count += 1
        else:
            count = limit
        count += 1  # 장시작/마감시간 고려하면 하나 더 얻어와야함
        request_items = (
            "date",
            "time",
            "open_price",
            "high_price",
            "low_price",
            "close_price",
            "volume",
        )
        item_pair = {
            "date": 0,
            "time": 1,
            "open_price": 2,
            "high_price": 3,
            "low_price": 4,
            "close_price": 5,
            "volume": 8,
            "volume_price": 9,
        }
        interval, unit = timeframe
        fill_gap = '1' if fill_gap else '0'
        use_adjusted_price = '1' if use_adjusted_price else '0'

        self.chart.set_input_value(0, code)
        self.chart.set_input_value(1, ord('2'))  # 갯수로 받아오는 것. '1'(기간)은 일봉만 지원
        self.chart.set_input_value(2,
                                   int(to.strftime("%Y%m%d")))  # 요청종료일 (가장 최근)
        self.chart.set_input_value(3, int(since.strftime("%Y%m%d")))  # 요청시작일
        self.chart.set_input_value(4, count)  # 요청갯수, 최대 2856 건
        self.chart.set_input_value(
            5, [item_pair.get(key) for key in request_items])
        self.chart.set_input_value(6, ord(
            unit.value))  # '차트 주기 ('D': 일, 'W': 주, 'M': 월, 'm': 분, 'T': 틱)
        self.chart.set_input_value(7, interval)  # 분/틱차트 주기
        self.chart.set_input_value(8, ord(fill_gap))  # 갭보정여부, 0: 무보정
        self.chart.set_input_value(9, use_adjusted_price)  # 수정주가여부, 1: 수정주가 사용
        self.chart.set_input_value(10, '1')  # 거래량 구분
        # '1': 시간외거래량모두포함, '2': 장종료시간외거래량만포함, '3': 시간외거래량모두제외, '4': 장전시간외거래량만포함

        self.chart.block_request()
        if self.chart.get_dib_status() != 0:
            self.__logger__.warning(self.chart.get_dib_msg1())
            return []

        chart_data = []
        row_cnt = self.chart.get_header_value(3)
        for i in range(row_cnt):
            resp = {
                "date": self.chart.get_data_value(0, i),
                "time": self.chart.get_data_value(1, i),
                "open": self.chart.get_data_value(2, i),
                "high": self.chart.get_data_value(3, i),
                "low": self.chart.get_data_value(4, i),
                "close": self.chart.get_data_value(5, i),
                "volume": self.chart.get_data_value(6, i),
            }
            candle: Candle = Candle(
                start_time=datetime(1970, 1, 1),
                end_time=datetime(1970, 1, 1),
                open_price=resp["open"],
                high_price=resp["high"],
                low_price=resp["low"],
                close_price=resp["close"],
                volume=resp["volume"],
            )
            if unit == TimeFrameUnit.MONTH:
                raise NotImplementedError()  # TODO
            elif unit == TimeFrameUnit.WEEK:
                date = str(resp["date"])
                year = int(date[:4])
                month = int(date[4:6])
                nth_week = int(date[6])
                nth_friday = Calendar(0).monthdatescalendar(year,
                                                            month)[nth_week][4]
                candle["start_time"] = datetime.strptime(
                    str(nth_friday), "%Y-%m-%d")
                candle["end_time"] = candle["start_time"] + timedelta(
                    weeks=1, hours=23, minutes=59)
            elif unit == TimeFrameUnit.DAY:
                candle["start_time"] = datetime.strptime(
                    str(resp["date"]), "%Y%m%d")
                candle["end_time"] = candle["start_time"] + timedelta(
                    hours=23, minutes=59)
            else:
                candle["end_time"] = datetime.strptime(
                    f'{resp["date"]}-{resp["time"]}', "%Y%m%d-%H%M")
                if candle["end_time"].hour == 15 and candle[
                        "end_time"].minute == 30:
                    if len(chart_data) > 0:
                        candle["start_time"] = chart_data[0]["end_time"]
                    else:
                        next_date = self.chart.get_data_value(0, i + 1)
                        next_time = self.chart.get_data_value(1, i + 1)
                        candle["start_time"] = datetime.strptime(
                            f'{next_date}-{next_time}', "%Y%m%d-%H%M")
                else:
                    candle["start_time"] = candle[
                        "end_time"] - timeframe_timedelta
            chart_data.insert(0, candle)
        for ohlcv in chart_data:
            if ((ohlcv["start_time"] - timeframe_timedelta) <
                    since) or ohlcv["end_time"] > to:
                chart_data.remove(ohlcv)
        return chart_data
Example #39
0
import calendar
from calendar import Calendar

# 返回一周内各天的名称
c1 = Calendar()  #不指定参数的话默认星期一(0 is Monday)
print("返回一周内各天的名称: ", list(c1.iterweekdays()))

c2 = Calendar(firstweekday=calendar.SATURDAY)  #指定今天是星期六
print("返回指定周几后一周内各天的名称: ", list(c2.iterweekdays()))

# 返回指定年,月的所有天数,会自动加上月前与月后的天数来令到每周都不会缺少日期(比如10.31是周三,会补上11.1,11.2与11.3来补全这一周)
# 返回的迭代器是以datetime.date为元素
print("返回指定年,月的所有天数(datetime.date): ", list(c2.itermonthdates(2018, 10)))

# 返回指定年,月的所有天数,不会自动加上月前与月后的天数来令到每周都不会缺少日期,缺少的天数为设为0
# 返回的迭代器是以int为元素
print("返回指定年,月的所有天数(int): ", list(c2.itermonthdays(2018, 10)))

# 返回指定年,月的所有天数,不会自动加上月前与月后的天数来令到每周都不会缺少日期,缺少的天数为设为0
# 返回的迭代器是以元组为元素, 元组里是(几号,星期x)这样
print("返回指定年,月的所有天数(tuple): ", list(c2.itermonthdays2(2018, 10)))

# 以周为单位返回指定年,月的所有天数,会自动加上月前与月后的天数来令到每周都不会缺少日期(比如10.31是周三,会补上11.1,11.2与11.3来补全这一周)
# 返回的列表是每七个datetime.date列表为元素
print("返回指定年,月的所有天数(tuple): ", c2.monthdatescalendar(2018, 10))
print(calendar.firstweekday())
print(calendar.isleap(2020))
print(calendar.leapdays(1900, 2100))
print(calendar.weekday(2019, 10, 1))
print(calendar.monthrange(2021,10))
print(calendar.monthcalendar(2019, 10))
print(calendar.prmonth(2021, 10))
print(calendar.prcal(2021))
print(calendar.day_name[0])
print(calendar.day_abbr[0])
print(calendar.month_name[1])
print(calendar.month_abbr[1])

print('--------------------------------')

c = Calendar()
print(list(c.itermonthdates(2021, 7)))
print(list(c.itermonthdays2(2020, 7)))
print(list(c.itermonthdays3(2021, 7)))
print(list(c.itermonthdays4(2021, 7)))

print('--------------------------------')

tx = TextCalendar()
print(tx.formatmonth(2021, 9))
print(tx.prmonth(2021, 9))
print(tx.formatyear(2021))
print(tx.pryear(2021))

print('---------------------------------')
Example #41
0
def handle_message(event):
    c = Calendar()
    if event.message.text == 'leaves':
        line_id = event.source.user_id
        user = StaffAccount.query.filter_by(line_id=line_id).first()
        if user:
            bubbles = []
            for quota in StaffLeaveQuota.query.filter_by(
                    employment_id=user.personal_info.employment.id):
                total_leaves = user.personal_info.get_total_leaves(
                    leave_quota_id=quota.id,
                    start_date=tz.localize(START_FISCAL_DATE),
                    end_date=tz.localize(END_FISCAL_DATE))
                bubbles.append(
                    BubbleContainer(
                        body=BoxComponent(
                            layout='vertical',
                            contents=[
                                TextComponent(text=u'{}'.format(
                                    quota.leave_type),
                                              weight='bold',
                                              size='xl',
                                              wrap=True),
                                FillerComponent(flex=2, ),
                                TextComponent(
                                    text=u'ใช้ไป {} วัน'.format(total_leaves),
                                    wrap=True,
                                    size='md')
                            ]),
                        footer=BoxComponent(
                            layout='vertical',
                            contents=[
                                ButtonComponent(action=URIAction(
                                    label=u'Make a request',
                                    uri='https://mumtmis.herokuapp.com')),
                            ])))
            line_bot_api.reply_message(
                event.reply_token,
                FlexSendMessage(alt_text='Leaves Info',
                                contents=CarouselContainer(contents=bubbles)))
    if event.message.text == 'events':
        today = datetime.today().date()
        this_week = []
        for week in c.monthdatescalendar(today.year, today.month):
            if today in week:
                this_week = [d for d in week]
                break
        events = requests.get(
            url_for('event.fetch_global_events', _external=True))
        bubbles = []
        for evt in events.json():
            start = dateutil.parser.parse(evt.get('start'))
            #TODO: recheck if .get file_id condition
            if evt.get('file_id'):
                event_id = evt.get('file_id')
            else:
                event_id = event_photo
            if start.date() in this_week:
                bubbles.append(
                    BubbleContainer(
                        hero=ImageComponent(
                            layout='vertical',
                            url="https://drive.google.com/uc?id={}".format(
                                event_id),
                            size='full',
                            aspect_mode='cover',
                            aspect_ratio='20:13',
                        ),
                        body=BoxComponent(
                            layout='vertical',
                            contents=[
                                TextComponent(text=u'{}'.format(
                                    evt.get('title')),
                                              weight='bold',
                                              size='xl',
                                              wrap=True),
                                TextComponent(
                                    text=u'วันที่ {} เวลา {} น.'.format(
                                        start.strftime(u'%d/%m/%Y'),
                                        start.strftime('%H:%M')),
                                    wrap=True),
                                TextComponent(text=u'สถานที่ {}'.format(
                                    evt.get('location') or u'ไม่ระบุ'),
                                              wrap=True),
                            ]),
                        footer=BoxComponent(
                            layout='vertical',
                            contents=[
                                ButtonComponent(
                                    action=URIAction(
                                        label=u'ลงทะเบียนกิจกรรมนี้ (Register)',
                                        uri=evt.get('registration')
                                        #uri='https://mt.mahidol.ac.th/calendar/events/'
                                    ), ),
                            ])))
        if bubbles:
            bubbles.append(
                BubbleContainer(
                    hero=ImageComponent(
                        layout='vertical',
                        url="https://drive.google.com/uc?id={}".format(
                            calendar_photo),
                        size='full',
                        aspect_mode='cover',
                        aspect_ratio='20:13',
                    ),
                    body=BoxComponent(
                        layout='vertical',
                        contents=[
                            ButtonComponent(action=URIAction(
                                label=u'ดูกิจกรรม (Event Detail)',
                                uri='https://mt.mahidol.ac.th/calendar/events/'
                            ), )
                        ])))
            line_bot_api.reply_message(
                event.reply_token,
                FlexSendMessage(alt_text='Events Info',
                                contents=CarouselContainer(contents=bubbles)))
        else:
            line_bot_api.reply_message(
                event.reply_token,
                FlexSendMessage(
                    alt_text='Events Info',
                    contents=CarouselContainer(contents=[
                        BubbleContainer(
                            body=BoxComponent(
                                layout='vertical',
                                contents=[
                                    TextComponent(
                                        text=u'ไม่มีกิจกรรมในสัปดาห์นี้',
                                        weight='bold',
                                        size='xl',
                                        wrap=True)
                                ]),
                            footer=BoxComponent(
                                layout='vertical',
                                contents=[
                                    ButtonComponent(action=URIAction(
                                        label=u'ดูปฏิทิน (Calendar)',
                                        uri=
                                        'https://mt.mahidol.ac.th/calendar/events/'
                                    )),
                                ]))
                    ])))
Example #42
0
import datetime as dt
from calendar import month_name, day_abbr, Calendar, monthrange

from urwid import Columns, GridFlow, Pile, Text, Padding, emit_signal, connect_signal, WEIGHT

from .fixed import Fixed
from .focus import FocusFor, FocusAttr, FocusWrap, OnFocus
from .state import ImmutableStatefulText, MutableStatefulText
from ...lib.date import format_date

MONTHS = month_name
DAYS2 = list(map(lambda d: day_abbr[d][:2], Calendar(0).iterweekdays()))
DAYS3 = list(map(lambda d: day_abbr[d][:3], Calendar(0).iterweekdays()))


def clip_day(day, month, year):
    return min(day, monthrange(year, month)[1])


class DateKeyPressMixin:
    """
    Assumes self.state is a date.

    default should be 'd', 'w', 'm', 'y', 'D' or 'M' (capitals support alpha selection)
    delta should be +1 or -1
    """
    def __init__(self, default, delta=1):
        self.__is_alpha = default.isupper()
        self.__default = default.lower()
        self.__delta = delta
Example #43
0
# Every folder or file behaves like a module in Python

# LIBRARY or MODULE BASED DATA TYPES/STRUCTURES

# # ARRAY

from array import array
var = array('i', [1, 2, 3])

# # DATE, CALENDER, etc

from datetime import date
var = date.today()

from calendar import Calendar
var = Calendar().iterweekdays()

# # CUSTOM TYPES


class MyOwnTypeImplementation():
    pass


# # DATA STRUCTURES

# 5.1.1. Using Lists as Stacks
# 5.1.2. Using Lists as Queues
# 5.1.3. List Comprehensions
# 5.1.4. Nested List Comprehensions
Example #44
0
def meetup_day(year, month, day_of_the_week, which):
    candidates = [date
                  for date in Calendar().itermonthdates(year, month)
                  if date.month == month
                  if date.strftime('%A') == day_of_the_week]
    return _choice(which)(candidates)
Example #45
0
 def test_blank_calendar(self):
     cal = Calendar()
     self.assertTrue(cal.lookup(0, 10))
Example #46
0
from calendar import Calendar, day_name
cal_inst = Calendar()
from datetime import date


def meetup_day(year, month, name_of_day, day_of_month):

    # take first day of month and add appropriate time according to arguments
    # adding arguments: name_of_day(M, Tu, W, Th, Fr, Sa, Su) & day_of_month(1st, 2nd, 3rd, 4th, teenth, last)

    # convert the names of days into a cardinal list --> [0-6]
    name_of_day_num_list = list(enumerate(day_name))
    for k, v in name_of_day_num_list:
        while name_of_day == v:
            name_of_day_num = k
            break
        else:
            pass

    #returns calendar iterator(tuple) for specified year, month (date.day#, wkday#)
    cal = list(cal_inst.itermonthdays2(year, month))

    #append a new list with all of that weekdays values (i.e. all Mondays, Tuesdays, etc.)
    new_list = [k for k, v in cal if v == name_of_day_num and k != 0]

    #enumerate new_list
    new_list = list(enumerate(new_list))

    #in this new_list, go through and select day that matched ordinal selections
    #if day_of_month == ordinal number
    #choose that number in list
Example #47
0
def make_calendar(year, month, firstweekday="Mon"):
    firstweekday = list(day_abbrs).index(firstweekday)
    calendar = Calendar(firstweekday=firstweekday)

    month_days = [
        None if not day else str(day)
        for day in calendar.itermonthdays(year, month)
    ]
    month_weeks = len(month_days) // 7

    workday = "linen"
    weekend = "lightsteelblue"

    def weekday(date):
        return (date.weekday() - firstweekday) % 7

    def pick_weekdays(days):
        return [days[i % 7] for i in range(firstweekday, firstweekday + 7)]

    day_names = pick_weekdays(day_abbrs)
    week_days = pick_weekdays([workday] * 5 + [weekend] * 2)

    source = ColumnDataSource(data=dict(
        days=list(day_names) * month_weeks,
        weeks=sum([[str(week)] * 7 for week in range(month_weeks)], []),
        month_days=month_days,
        day_backgrounds=sum([week_days] * month_weeks, []),
    ))

    holidays = [
        (date, summary.replace("(US-OPM)", "").strip())
        for (date, summary) in us_holidays
        if date.year == year and date.month == month and "(US-OPM)" in summary
    ]

    holidays_source = ColumnDataSource(data=dict(
        holidays_days=[day_names[weekday(date)] for date, _ in holidays],
        holidays_weeks=[
            str((weekday(date.replace(day=1)) + date.day) // 7)
            for date, _ in holidays
        ],
        month_holidays=[summary for _, summary in holidays],
    ))

    xdr = FactorRange(factors=list(day_names))
    ydr = FactorRange(
        factors=list(reversed([str(week) for week in range(month_weeks)])))
    x_scale, y_scale = CategoricalScale(), CategoricalScale()

    plot = Plot(x_range=xdr,
                y_range=ydr,
                x_scale=x_scale,
                y_scale=y_scale,
                plot_width=300,
                plot_height=300,
                outline_line_color=None)
    plot.title.text = month_names[month]
    plot.title.text_font_size = "12pt"
    plot.title.text_color = "darkolivegreen"
    plot.title.offset = 25
    plot.min_border_left = 0
    plot.min_border_bottom = 5

    rect = Rect(x="days",
                y="weeks",
                width=0.9,
                height=0.9,
                fill_color="day_backgrounds",
                line_color="silver")
    plot.add_glyph(source, rect)

    rect = Rect(x="holidays_days",
                y="holidays_weeks",
                width=0.9,
                height=0.9,
                fill_color="pink",
                line_color="indianred")
    rect_renderer = plot.add_glyph(holidays_source, rect)

    text = Text(x="days",
                y="weeks",
                text="month_days",
                text_align="center",
                text_baseline="middle")
    plot.add_glyph(source, text)

    xaxis = CategoricalAxis()
    xaxis.major_label_text_font_size = "8pt"
    xaxis.major_label_standoff = 0
    xaxis.major_tick_line_color = None
    xaxis.axis_line_color = None
    plot.add_layout(xaxis, 'above')

    hover_tool = HoverTool(renderers=[rect_renderer],
                           tooltips=[("Holiday", "@month_holidays")])
    plot.tools.append(hover_tool)

    return plot
Example #48
0
# Created by nijianfeng at 18/6/17

import time
import calendar
from calendar import Calendar

# http://www.runoob.com/python3/python3-date-time.html

# 时间操作
localtime = time.localtime(time.time())
print("本地时间为 :", time.asctime(localtime))
print("本地时间为 :", localtime)
# 格式化成2016-03-20 11:45:39形式
print(time.strftime("%Y-%m-%d %H:%M:%S", localtime))
# 格式化成Sat Mar 28 22:24:24 2016形式
print(time.strftime("%a %b %d %H:%M:%S %Y", localtime))
# 将格式字符串转换为时间戳
print(
    time.mktime(
        time.strptime("Sat Mar 28 22:24:24 2016", "%a %b %d %H:%M:%S %Y")))

# 日历操作
print()
cal_str = calendar.month(2018, 6)
print("以下输出2018年6月份的日历:\n", cal_str)
cal = Calendar()
print(",".join([str(v) for v in cal.iterweekdays()]))
# 是否闰年
print()
print(calendar.isleap(2018))
Example #49
0
    def get_context_data(self, **kwargs):
        """
        Injects variables necessary for rendering the calendar into the context.

        Variables added are: `calendar`, `weekdays`, `month`, `next_month` and `previous_month`.
        """
        data = super(BaseCalendarMonthView, self).get_context_data(**kwargs)

        year = self.get_year()
        month = self.get_month()

        date = _date_from_string(year, self.get_year_format(), month,
                                 self.get_month_format())

        cal = Calendar(self.get_first_of_week())

        month_calendar = []
        now = datetime.datetime.utcnow()

        date_lists = defaultdict(list)
        multidate_objs = []

        for obj in data['object_list']:
            obj_date = self.get_start_date(obj)
            end_date_field = self.get_end_date_field()

            if end_date_field:
                end_date = self.get_end_date(obj)
                if end_date and end_date != obj_date:
                    multidate_objs.append({
                        'obj':
                        obj,
                        'range': [x for x in daterange(obj_date, end_date)]
                    })
                    continue  # We don't put multi-day events in date_lists
            date_lists[obj_date].append(obj)

        for week in cal.monthdatescalendar(date.year, date.month):
            week_range = set(daterange(week[0], week[6]))
            week_events = []

            for val in multidate_objs:
                intersect_length = len(week_range.intersection(val['range']))

                if intersect_length:
                    # Event happens during this week
                    slot = 1
                    width = intersect_length  # How many days is the event during this week?
                    nowrap_previous = True  # Does the event continue from the previous week?
                    nowrap_next = True  # Does the event continue to the next week?

                    if val['range'][0] >= week[0]:
                        slot = 1 + (val['range'][0] - week[0]).days
                    else:
                        nowrap_previous = False
                    if val['range'][-1] > week[6]:
                        nowrap_next = False

                    week_events.append({
                        'event': val['obj'],
                        'slot': slot,
                        'width': width,
                        'nowrap_previous': nowrap_previous,
                        'nowrap_next': nowrap_next,
                    })

            week_calendar = {
                'events': week_events,
                'date_list': [],
            }
            for day in week:
                week_calendar['date_list'].append({
                    'day':
                    day,
                    'events':
                    date_lists[day],
                    'today':
                    day == now.date(),
                    'is_current_month':
                    day.month == date.month,
                })
            month_calendar.append(week_calendar)

        data['calendar'] = month_calendar
        data['weekdays'] = [DAYS[x] for x in cal.iterweekdays()]
        data['month'] = date
        data['next_month'] = self.get_next_month(date)
        data['previous_month'] = self.get_previous_month(date)

        return data
Example #50
0
import django

django.setup()

import random
from django.utils import timezone
from datetime import datetime
from calendar import Calendar

from reference_stats.models import Request, TypeOfRequest, Medium
from accounts.models import User, Branch
from faker import Faker

fakegen = Faker()

cal = Calendar()


def add_requests(N=5,
                 iteryear=2017,
                 itermonth=12):  #N is the number of requests per day

    totaldays = 0
    for day in cal.itermonthdates(iteryear, itermonth):
        totaldays = totaldays + 1

    totalusers = 0
    for profile in User.objects.all():
        if profile.is_superuser == False:
            totalusers = totalusers + 1
 def get_day(year: int, month: int, week: int, day_of_week: DayOfWeek) -> int:
     calendar = Calendar()
     return [d for d in calendar.itermonthdays2(year, month) if d[0] and d[1] == day_of_week-1][week][0]
Example #52
0
from calendar import Calendar

cal = Calendar(firstweekday=6)


def monthdates_cal(yr, m):
    '''
    creates a 1 month list of weeks where the days are datetime.date objects
    :param yr: year
    :param m: month
    :return: [datetime.date(2017-10-25), ...][.....]
    '''
    monthdates = cal.monthdatescalendar(yr, m)
    return monthdates


# returns the week of days as datetime.date objects containing the search date from a larger calendar
def weekdates_cal(monthcal, finddate):
    '''
    creates a 1 week list of days (datetime.date objects) of the week containing the finddate. Sun-Sat of the week
    :param monthcal: takes in a Calendar.monthdatescalendar list
    :param finddate: the date that is within the week which is to be returned. format yyyy-mm-d
    :return: [datetime.date(2017-10-25), ...][.....]
    '''
    calweek = []
    for week in monthcal:
        if finddate in week:
            for day in week:
                calweek.append(day)
    return calweek
Example #53
0
    def get_context_sets(self, max_start_date: datetime.date,
                         min_end_date: datetime.date) -> List:
        """Get context sets defined by the Rules context and subject"""
        # if period is bounded, start and end dates are already bounded by period
        period_start_date = self.group.period.start_date

        if self.context == RuleContext.PERIOD:
            if not period_start_date:
                raise Exception(
                    "Period rule not applicable to period without start.")

            if self.subject == RuleSubject.DAY:
                return [expand_range(max_start_date, min_end_date)]

            elif self.subject == RuleSubject.WEEK:
                week_start = period_start_date - relativedelta(
                    days=period_start_date.weekday())
                week_end = week_start + relativedelta(weekday=SU(1))

                weeks = []
                while week_start <= min_end_date:
                    weeks.append(expand_range(week_start, week_end))
                    week_start = week_start + relativedelta(weeks=1)
                    week_end = week_start + relativedelta(weekday=SU(1))

                return [weeks]

            elif self.subject == RuleSubject.MONTH:
                first_day = datetime.date(
                    year=period_start_date.year,
                    month=period_start_date.month,
                    day=1,
                )
                last_day_of_month = first_day + relativedelta(day=31)

                months = []
                while last_day_of_month <= min_end_date + relativedelta(
                        day=31):
                    months.append(expand_range(first_day, last_day_of_month))
                    first_day += relativedelta(months=1)
                    last_day_of_month = first_day + relativedelta(day=31)

                return [months]

            elif self.subject in RuleSubject.weekday_subjects():
                dates = []
                for a_date in expand_range(period_start_date, min_end_date):
                    if a_date.isoweekday() == self.subject.as_isoweekday():
                        dates.append(a_date)

                return [dates]

        elif self.context == RuleContext.YEAR:
            years = range(max_start_date.year, min_end_date.year + 1)

            result = []
            for year in years:
                if self.subject == RuleSubject.DAY:
                    result.append(
                        expand_range(
                            datetime.date(year=year, month=1, day=1),
                            datetime.date(year=year, month=12, day=31),
                        ))
                elif self.subject == RuleSubject.WEEK:
                    year_start_date = datetime.date(year=year, month=1, day=1)
                    week_start = year_start_date - relativedelta(
                        days=year_start_date.weekday())
                    week_end = week_start + relativedelta(weekday=SU(1))

                    weeks = []
                    while week_start <= min_end_date:
                        weeks.append(expand_range(week_start, week_end))
                        week_start = week_start + relativedelta(weeks=1)
                        week_end = week_start + relativedelta(weekday=SU(1))

                    result.append(weeks)
                elif self.subject == RuleSubject.MONTH:
                    months = []
                    for month_number in range(1, 13):
                        first_day_of_month = datetime.date(year=year,
                                                           month=month_number,
                                                           day=1)
                        last_day_of_month = first_day_of_month + relativedelta(
                            day=31)
                        months.append(
                            expand_range(first_day_of_month,
                                         last_day_of_month))

                    result.append(months)
                elif self.subject in RuleSubject.weekday_subjects():
                    days_in_year = expand_range(
                        datetime.date(year=year, month=1, day=1),
                        datetime.date(year=year, month=12, day=31),
                    )
                    dates = []
                    for a_date in days_in_year:
                        if a_date.isoweekday() == self.subject.as_isoweekday():
                            dates.append(a_date)

                    result.append(dates)

            return result

        elif self.context == RuleContext.MONTH:
            c = Calendar()

            first_day = datetime.date(year=max_start_date.year,
                                      month=max_start_date.month,
                                      day=1)
            last_day_of_month = first_day + relativedelta(day=31)

            result = []
            while last_day_of_month <= min_end_date + relativedelta(day=31):
                if self.subject == RuleSubject.DAY:
                    days_in_month = expand_range(first_day, last_day_of_month)
                    result.append(days_in_month)
                elif self.subject == RuleSubject.WEEK:
                    weeks_in_month = c.monthdatescalendar(
                        first_day.year, first_day.month)
                    result.append(weeks_in_month)

                elif self.subject == RuleSubject.MONTH:
                    raise ValueError("Not applicable")

                elif self.subject in RuleSubject.weekday_subjects():
                    days_in_month = expand_range(first_day, last_day_of_month)

                    dates = []
                    for a_date in days_in_month:
                        if a_date.isoweekday() == self.subject.as_isoweekday():
                            dates.append(a_date)

                    result.append(dates)

                first_day += relativedelta(months=1)
                last_day_of_month = first_day + relativedelta(day=31)
            return result
Example #54
0
def book_lesson():
    '''这是学生订课的视图'''
    # 找到该学生的老师
    teacher = User.query.filter_by(
        id=current_user.student_profile.first().teacher_id).first()
    # 学生可能还没有分配老师,我们只操作分配了老师的情况
    if teacher:
        #取出老师的工作时间字符串并转化为列表
        worktime = teacher.work_time.first().work_time
        worktime_list = worktime.split(';')

        #把以星期为单位的教师工作时间转化为UTC年月日小时的时间
        #第一步:构造出UTC的此时此刻
        cal = Calendar(6)  # 让每个星期都从星期天开始
        utc = timezone('UTC')
        utcnow = datetime.utcnow()
        utcnow = datetime(utcnow.year,
                          utcnow.month,
                          utcnow.day,
                          utcnow.hour,
                          tzinfo=utc)
        # 第二步:计算出可以选课的起始时间,也就是此时此刻的24小时后,以及截至时间,也就是现在开始的29天后
        available_start = utcnow + timedelta(1)
        available_end = utcnow + timedelta(29)
        # 第三步:找到起始日期和结束日期所在的星期,拼接出可以选课的28天的列表,
        # 大列表里的小列表代表一个个以周日开始的星期
        start_flag = False
        all_available_dates = []
        for week in cal.monthdatescalendar(available_start.year,
                                           available_start.month):
            # 在没找到起始日期所在的星期的时候,要检查这个星期是否就是我们寻找的
            if not start_flag and available_start.date() in week:
                start_flag = True
            # 从找到了起始日期所在的星期开始,我们要把它所在的以及它后面的星期加到列表里
            if start_flag:
                all_available_dates.append(week)

        # 遍历结束日期所在的月,如果当前星期不在列表里,就添加(因为前后两个月可能有重复的星期)
        # 遇到结束日期所在的星期,后面的就不用看了
        for week in cal.monthdatescalendar(available_end.year,
                                           available_end.month):
            if available_end not in week:
                all_available_dates.append(week)
            if available_end.date() in week:
                break

        # 第四步:根据老师的工作时间,构造出以datetime对象为元素的列表
        # 创建一个空列表,存放老师的以小时为单位的工作时间
        new_worktime_list = []
        for week in all_available_dates:
            # w是类似于0-1这样的字符串,它表示星期天的UTC时间1点钟
            for w in worktime_list:
                date = week[int(w[0])]
                time = datetime(date.year,
                                date.month,
                                date.day,
                                int(w[2:]),
                                tzinfo=utc)
                if time < available_start or time > available_end:
                    continue
                new_worktime_list.append(time)
        # 第五步:把教师的特殊休息时间去掉
        special_rest_set = set()
        temp = teacher.special_rest.filter_by(expire=False).all()
        for data in temp:
            rest_time = datetime(data.rest_time.year,
                                 data.rest_time.month,
                                 data.rest_time.day,
                                 data.rest_time.hour,
                                 tzinfo=utc)
            if rest_time >= available_start:
                special_rest_set.add(rest_time)
            else:
                data.expire = True
                db.session.add(data)
        for i in new_worktime_list[:]:
            if i in special_rest_set:
                new_worktime_list.remove(i)
        # 第六步:把教师的补班时间加进去(这一步要放在前面,因为可能补班的时间也被选上课了)
        makeup_time_list = []
        # 先把当前显示没有过期的补班时间都查出来
        temp = teacher.make_up_time.filter_by(expire=False).all()
        for data in temp:
            makeup_time = datetime(data.make_up_time.year,
                                   data.make_up_time.month,
                                   data.make_up_time.day,
                                   data.make_up_time.hour,
                                   tzinfo=utc)
            if makeup_time >= available_start:
                makeup_time_list.append(makeup_time)
            # 如果补班时间在可选开始时间之前,说明事实上已经过期了
            # 把expire改为True
            else:
                data.expire = True
                db.session.add(data)

        new_worktime_list += makeup_time_list
        # 第七步:生成一个已预约的课程时间列表,并把这些时间从老师的工作时间里去掉
        # 为了节约资源,我们在查询的时候就筛选一下时间
        lessons = Lesson.query.filter(
            Lesson.teacher_id == teacher.id, Lesson.is_delete == False,
            Lesson.time >= datetime.utcnow() + timedelta(1)).all()
        # 先用set存放时间,因为查询比较快
        lessons_set = set()
        for lesson in lessons:
            time = lesson.time
            time = datetime(time.year,
                            time.month,
                            time.day,
                            time.hour,
                            tzinfo=utc)
            lessons_set.add(time)
        for i in new_worktime_list[:]:
            if i in lessons_set:
                new_worktime_list.remove(i)
        lessons_list = list(lessons_set)

        #计算出游客的时区
        visitor_country = current_user.timezone
        if len(visitor_country) > 2:
            visitor_tz = country_timezones[visitor_country[:2]][int(
                visitor_country[-1])]
        else:
            visitor_tz = country_timezones[visitor_country][0]
        tz_obj = timezone(visitor_tz)

        # 根据时区,生成游客视角的可以选课的28天的日历
        visitor_start = get_localtime(available_start, current_user)
        visitor_end = get_localtime(available_end, current_user)

        visitor_dates = []
        start_flag = False
        for week in cal.monthdatescalendar(visitor_start.year,
                                           visitor_start.month):
            # 因为遍历一个星期也会浪费时间,所以我们这里设两个条件
            # 如果flag已经是True了,就不需要再看结束日期在不在这个星期里了
            if not start_flag and visitor_start.date() in week:
                start_flag = True
            if start_flag:
                visitor_dates.append(week)
        # 因为前后两个月可能有重复的星期,所以要判断是否在列表里,不在的才添加
        for week in cal.monthdatescalendar(visitor_end.year,
                                           visitor_end.month):
            if week not in visitor_dates:
                visitor_dates.append(week)
            # 如果已经到了结束日期所在的星期,就不用看后面的了
            if visitor_end.date() in week:
                break

        # 获取页码
        page = request.args.get('page', 1, type=int)
        # 如果有用户恶意修改页码,我们要把页码变成1
        if page > len(visitor_dates) or page < 1:
            page = 1

        # 每个星期的月份和年,应该以这个星期中间的那一天为标准
        current_page = Pagination(visitor_dates, page, 1, len(visitor_dates),
                                  visitor_dates[page - 1])
        middle_day = current_page.items[3]
        month_name = calendar.month_name[middle_day.month]
        year = middle_day.year

        this_week = []
        only_dates = []

        for date in current_page.items:
            this_week.append('%s-%s-%s' % (date.year, date.month, date.day))
            only_dates.append(date.day)

        #把老师的可选的时间列表换成游客时区的时间(字符串)
        for i, time in enumerate(new_worktime_list):
            time = time.astimezone(tz_obj)
            new_worktime_list[i] = '%s-%s-%s-%s' % (time.year, time.month,
                                                    time.day, time.hour)
        #把老师有课的时间转换成游客时区的时间(字符串)
        for i, time in enumerate(lessons_list):
            time = time.astimezone(tz_obj)
            lessons_list[i] = '%s-%s-%s-%s' % (time.year, time.month, time.day,
                                               time.hour)

        # 查看并处理选课的ajax请求
        time = request.form.get('time', '', type=str)
        if time:
            time = time.split('-')
            #先构造一个没有时区的datetime对象
            time = datetime(int(time[0]), int(time[1]), int(time[2]),
                            int(time[3]))
            #再把它变成时区为游客所在地区的datetime对象
            time = tz_obj.localize(time)
            #再把时区变成utc时区
            time = time.astimezone(utc)

            # 再判断一次是否在可选时间范围内
            if time >= available_start:
                # 看看学生的课时包里是否还有课
                active_package = current_user.orders.filter(
                    Order.pay_status == 'paid',
                    Order.left_amount > 0).order_by(Order.id.asc()).first()
                if active_package:
                    # 课时包的课程数量扣掉一节
                    active_package.left_amount -= 1
                    db.session.add(active_package)
                    # 把选课信息存进数据库
                    lesson = current_user.lessons.filter(
                        Lesson.time == time,
                        Lesson.teacher_id == teacher.id).first()
                    if lesson:
                        lesson.is_delete = False
                    else:
                        lesson = Lesson()
                        lesson.student_id = current_user.id
                        lesson.teacher_id = teacher.id
                        lesson.time = time
                        lesson.message = ''
                        lesson.lesson_type = active_package.lesson_type
                    db.session.add(lesson)
                    return jsonify({
                        'status':
                        'ok',
                        'msg':
                        "You've successfully booked a lesson."
                    })
                else:
                    return jsonify({
                        'status':
                        'fail',
                        'msg':
                        "You don't have any lessons now. Please buy another package."
                    })
            else:
                return jsonify({
                    'status':
                    'fail',
                    'msg':
                    'You need to book lessons not earlier than 24 hours from now.'
                })
        return render_template('student/book_lesson.html',
                               teacher=teacher,
                               this_week=this_week,
                               only_dates=only_dates,
                               new_worktime_list=new_worktime_list,
                               month_name=month_name,
                               year=year,
                               current_page=current_page,
                               lessons_list=lessons_list)

    return render_template('student/book_lesson.html', teacher=teacher)
Example #55
0
    def get_context_data(self, **kwargs):
        def get_weekday_text(athlete, weekday):
            morph = pymorphy2.MorphAnalyzer()
            if athlete.week_day:
                for week_day in eval(athlete.week_day):
                    if weekday < int(week_day):
                        day_text = morph.parse(
                            Athlete.WEEK_DAYS[int(week_day)][1])[0].inflect(
                                {'accs'}).word
                        return 'во' if Athlete.WEEK_DAYS[int(
                            week_day)][0] == 1 else 'в', day_text
                day_text = morph.parse(Athlete.WEEK_DAYS[int(
                    eval(athlete.week_day)[0])][1])[0].inflect({'accs'}).word
                return 'во' if Athlete.WEEK_DAYS[int(
                    eval(athlete.week_day)[0])][0] == 1 else 'в', day_text
            return 'не', 'запланирована'

        athlete = Athlete.objects.get_or_create(user=self.request.user)[0]
        today = datetime.now().date()
        cal = Calendar(MONDAY)
        year = int(self.kwargs.get('year'))
        month = int(self.kwargs.get('month'))
        day = int(self.kwargs.get('day'))
        current_date = date(year, month, day)
        next_month = add_months(current_date, 1)
        prev_month = sub_months(current_date, 1)
        month_dates = list(cal.itermonthdates(year, month))
        trainings = Training.objects.filter(date__in=month_dates,
                                            workout_diary=self.object)
        month_dates_with_training = [
            (item, True) if athlete.week_day and item >= today
            and str(item.weekday()) in athlete.week_day else
            (item, trainings.filter(date=item).last()) for item in month_dates
        ]
        splited = chunks(month_dates_with_training, 7)
        month = [(week[0][0].isocalendar()[1] == today.isocalendar()[1], week)
                 for week in splited]
        training_today = athlete.week_day and (str(today.weekday())
                                               in athlete.week_day)
        training = get_training(self.request.user, current_date)
        ctx = {
            'training':
            training,
            'today':
            today,
            'month':
            month,
            'prev_month':
            prev_month,
            'next_month':
            next_month,
            'current_month':
            month_text(current_date.month),
            'current_date':
            current_date,
            'current_weekday':
            Athlete.WEEK_DAYS[current_date.weekday()][1],
            'training_duration':
            athlete.get_training_duration_display(),
            'history':
            current_date < today,
            'training_today':
            training_today,
            'button_text': (True, 'Начать тренировку') if training_today else
            (False, 'Следующая тренировка %s %s' %
             get_weekday_text(athlete=athlete, weekday=today.weekday()))
        }
        return ctx