def get_fechas(self): now = date.today() self.fin = date(now.year, now.month, calendar.monthrange(now.year, now.month)[1]) self.inicio = date(now.year, now.month, 1) self.inicio = datetime.combine(self.inicio, time.min) self.fin = datetime.combine(self.fin, time.max)
def getRessourceDispo(ressource,date): day = date.strftime("%a").upper()[0:2] dispo = Event.objects.filter(rule=day).filter(ressources=ressource).order_by("start") dispo = getContinuEvent(dispo) occupation = Event.objects.filter(start__contains=date.strftime("%Y-%m-%d")).filter(ressources=ressource).exclude(type="DISPONIBLE").order_by("start") occupation = getContinuEvent(occupation) for d in dispo: d.start = datetime.combine(date.date(),d.start.time()) d.end = datetime.combine(date.date(),d.end.time()) return getDispo(dispo,occupation)
def delete_urlaubsschicht(sender, instance, created, **kwargs): time = localtime().replace(hour=0, minute=0, second=0, microsecond=0) # DELETE-query Schicht.objects.filter(beginn__range=( datetime.combine(instance.beginn, time), datetime.combine(instance.ende + timedelta(days=1), time) )).filter(assistent=instance.assistent).delete() | Schicht.objects.filter( ende__range=(datetime.combine(instance.beginn, time), datetime.combine(instance.ende + timedelta(days=1), time) )).filter(assistent=instance.assistent).delete()
def make_date_aware(d=None, timezone=utc): # rendre la date entrée "aware" en utc if d is None: return make_aware(datetime_safe.now(), timezone=timezone) elif type(d) is str: return make_aware(datetime_safe.combine(parse_date(d), time(0, 0, 0)), timezone=timezone) elif type(d) is datetime_date or type(d) is datetime_classic: return make_aware(datetime_safe.combine(d, time(0, 0, 0)), timezone=timezone) return d
def dispatch(self, request, *args, **kwargs): tz = timezone.get_current_timezone() now = timezone.now() day = timedelta(days=1) self.yesterday = now - day self.today = tz.localize(datetime.combine(now, time.min)) self.fin = date(now.year, now.month, calendar.monthrange(now.year, now.month)[1]) self.inicio = date(now.year, now.month, 1) self.inicio = tz.localize(datetime.combine(self.inicio, time.min)) self.fin = tz.localize(datetime.combine(self.fin, time.max)) return super(ConsultorioDetailView, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): tz = timezone.get_current_timezone() now = timezone.now() day = timedelta(days=1) self.yesterday = now - day self.today = tz.localize(datetime.combine(now, time.min)) self.fin = date(now.year, now.month, calendar.monthrange(now.year, now.month)[1]) self.inicio = date(now.year, now.month, 1) self.inicio = tz.localize(datetime.combine(self.inicio, time.min)) self.fin = tz.localize(datetime.combine(self.fin, time.max)) return super(ConsultorioIndexView, self).dispatch(request, *args, **kwargs)
def goals(request): start = time.time() if request.method == "POST": form = GoalFilterForm(request.POST) else: form = GoalFilterForm() if form.is_valid(): all_goals = form.query() else: all_goals = Goal.objects.all() for g in all_goals: g.deadline = datetime.combine(g.deadline, WORK_HOURS_END) end = time.time() return render( request, template_name="meals/goal/goal.html", context={ "all_goals": all_goals, "form": form, "seconds": f"{end - start:6.3f}", }, )
def testCreateLoan(self): from ..models import Contract user = self.user_test digital_work = DigitalWork(user=self.user_test, digital_work_file=FIX_URL_JPG, digital_work_hash='hash') digital_work.save() thumbnail = Thumbnail(user=self.user_test, key=FIX_URL_JPG) thumbnail.save() root_piece, editions = APIUtilPiece.create_piece( user, title='title', artist_name='artist_name', num_editions=2, thumbnail=thumbnail, digital_work=digital_work) save_loan = Loan.create(editions[0], self.user_admin, owner=editions[0].owner) save_loan.prev_btc_address = 'dsdfas' save_loan.new_btc_address = 'asdsad' save_loan.datetime_from = datetime.combine( self.date, datetime.min.time()).replace(tzinfo=pytz.UTC) save_loan.datetime_to = datetime.combine( self.date, datetime.min.time()).replace(tzinfo=pytz.UTC) save_loan.save() save_file = OtherData.objects.create(user=self.user_test, key=FIX_KEY_PNG) contract = Contract.objects.create(issuer=self.user_test, blob=save_file) loan_details = LoanDetail(loan=save_loan, gallery="gallery", contract_model=contract) loan_details.save() find_loan = Loan.objects.get(id=save_loan.id) compare_ownerships(self, save_loan, find_loan) compare_loan_details(self, save_loan.details, find_loan.details) self.assertEqual(save_loan.details.contract_model.blob.key, FIX_KEY_PNG)
def dispatch(self, request, *args, **kwargs): self.form = PeriodoForm(request.GET, prefix='cargo-periodo') if self.form.is_valid(): self.inicio = self.form.cleaned_data['inicio'] self.fin = datetime.combine(self.form.cleaned_data['fin'], time.max) self.cargos = Cargo.objects.filter(created__gte=self.inicio, created__lte=self.fin) return super(CargoPeriodoView, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): self.form = PeriodoForm(request.GET, prefix='cargo-periodo') if self.form.is_valid(): self.inicio = self.form.cleaned_data['inicio'] self.fin = datetime.combine(self.form.cleaned_data['fin'], time.max) self.cargos = Cargo.objects.filter( created__gte=self.inicio, created__lte=self.fin ) return super(CargoPeriodoView, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): self.form = PeriodoForm(request.GET, prefix='evaluacion-periodo') if self.form.is_valid(): self.inicio = self.form.cleaned_data['inicio'] self.fin = datetime.combine(self.form.cleaned_data['fin'], time.max) self.evaluaciones = Evaluacion.objects.filter( created__gte=self.inicio, created__lte=self.fin).order_by('paciente__consultorio') return super(EvaluacionPeriodoView, self).dispatch(request, *args, **kwargs)
def get_midnight(dt, offset): """ Return the UTC time corresponding to midnight in local time for the day specified, offset forward by the specified number of days (eg. offset=0 -> last midnight, offset=1 -> next midnight etc) @param dt: <datetime> The datetime you are converting to midnight @return: Aware <datetime> """ current_tz = get_current_timezone() local = current_tz.normalize(dt.astimezone(current_tz)) # Convert to local time before processing to get next local midnight o = datetime.combine(local + timedelta(days=offset), time(0, 0, 0)) return make_aware(o, get_current_timezone())
def dispatch(self, request, *args, **kwargs): self.form = PeriodoForm(request.GET, prefix='evaluacion-periodo') if self.form.is_valid(): self.inicio = self.form.cleaned_data['inicio'] self.fin = datetime.combine(self.form.cleaned_data['fin'], time.max) self.evaluaciones = Evaluacion.objects.filter( created__gte=self.inicio, created__lte=self.fin ).order_by('paciente__consultorio') return super(EvaluacionPeriodoView, self).dispatch(request, *args, **kwargs)
def index(request): form = RecordModelForm(request.POST or None) if form.is_valid(): data = form.save() messages.success( request, 'Вы успешно записаны ко врачу {0}' ' на {1:%H:%M} {1:%d.%m.%Y}'.format( data.doctor.name, datetime.combine(data.date, data.time) ) ) return redirect(reverse('index')) return render(request, 'base.html', {'form': form, 'settings': settings})
def dispatch(self, request, *args, **kwargs): """Filtra las :class:`Emergencia` de acuerdo a los datos ingresados en el formulario""" self.form = PeriodoForm(request.GET, prefix='consulta') if self.form.is_valid(): self.inicio = self.form.cleaned_data['inicio'] self.fin = datetime.combine(self.form.cleaned_data['fin'], time.max) self.consultas = Consulta.objects.filter( created__range=(self.inicio, self.fin) ) else: return redirect('invoice-index') return super(ConsultaPeriodoView, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): """Filtra las :class:`Emergencia` de acuerdo a los datos ingresados en el formulario""" self.form = PeriodoForm(request.GET, prefix='consulta') if self.form.is_valid(): self.inicio = self.form.cleaned_data['inicio'] self.fin = datetime.combine(self.form.cleaned_data['fin'], time.max) self.consultas = Consulta.objects.filter( created__range=(self.inicio, self.fin)) else: return redirect('invoice-index') return super(ConsultaPeriodoView, self).dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs): issue = get_object_or_404(Issue, pk=kwargs['pk']) form = HackathonCreateForm(request.POST, request.FILES) is_vaild = form.is_valid() if is_vaild: due_date = form.cleaned_data['due_date'] due_time = form.cleaned_data['due_time'] hackathon = form.save(commit=False) hackathon.due_date_time = datetime.combine(due_date, due_time) hackathon.host = request.user hackathon.contribute_to = issue hackathon.save() return redirect("hackathons:detail", hackathon.pk) return redirect("hackathons:create")
def validate_input(start_date, start_time, duration, student, number_people, refrigerator, occasion): start_datetime = datetime.combine(start_date, start_time) end_datetime = start_datetime + dt.timedelta(hours=duration) today = datetime.today() if start_datetime < today: raise ValidationError(_('You cant book events in the past'), 'unavailable_timeslot') today += relativedelta(months=+6) if start_datetime > today: raise ValidationError(_('You cant book so far in the future'), 'unavailable_timeslot') if not timeslot_available(start_datetime, end_datetime): raise ValidationError(_('Es gibt bereits eine Buchung zu diesem Zeitpunkt.'), 'unavailable_timeslot') day_type = get_day_type(start_date) if (day_type == 'WEEKDAY') and duration not in [3, 6, 12]: raise ValidationError(_('An Wochentagen ist nur eine 3-,6- oder 12-stündige Buchung möglich.'), 'invalid_duration') elif (day_type == 'WEEKEND') and duration not in [12, 24]: raise ValidationError(_('An Wochenenden ist nur eine 12- oder 24-stündige Buchung möglich.'), 'invalid_duration') if start_time < dt.time(8, 0): raise ValidationError(_('Eine Buchung ist erst ab 8 Uhr (Mo-Fr) bzw. 16 Uhr (Sa-So) möglich.')) if start_time.minute != 0: raise ValidationError(_('Buchungen können nur zur vollen Stunde beginnen.'), 'invalid_starttime') if number_people <= 0: raise ValidationError(_('Die Anzahl erscheinender Personen muss größer als 0 sein.'), 'invalid_people_num') if student != 'yes' and student != 'no': raise ValidationError(_('Ungültige Eingabe bei Studentenfrage.'), 'invalid_student_input') if refrigerator != 'yes' and refrigerator != 'no': raise ValidationError(_('Ungültige Eingabe bei Kühlschrankfrage.'), 'invalid_refrigerator_input') if occasion == '': raise ValidationError(_('Das Feld zum Anlass darf nicht leer sein.'), 'empty_occasion')
def sort_schichten_in_templates(self): splitted_templates = [] templates = get_schicht_templates(asn=self.request.user.assistenznehmer, order_by='beginn') # Todo Sub-Templates und verschobene Templates for template in templates: if template.beginn < template.ende: splitted_templates.append( { 'beginn': template.beginn, 'ende': template.ende } ) else: splitted_templates.append( { 'beginn': template.beginn, 'ende': time(0) } ) splitted_templates.append( { 'beginn': time(0), 'ende': template.ende } ) splitted_templates = sorted(splitted_templates, key=lambda j: j['beginn']) start = self.act_date # schichtsammlung durch ergänzung von leeren Tagen zu Kalender konvertieren end = shift_month(self.act_date, step=1) monatsletzter = (end - timedelta(days=1)).day schichten = get_sliced_schichten_by_asn( start=self.act_date, end=end, asn=self.request.user.assistenznehmer ) table_array = {} for i in range(1, monatsletzter + 1): datakey = datetime(year=self.act_date.year, month=self.act_date.month, day=i) template_counter = 0 table_array[datakey] = {} for template in splitted_templates: temp_beginn = timezone.make_aware(datetime.combine(datakey, template['beginn'])) if template['ende'] == time(0): temp_ende = timezone.make_aware( datetime.combine( datakey + timedelta(days=1), template['ende'] ) ) else: temp_ende = timezone.make_aware(datetime.combine(datakey, template['ende'])) table_array[datakey][template_counter] = [] schicht_counter = 0 for schicht in schichten: # print(temp_beginn) # print(schicht['beginn']) # print(temp_ende) # print(schicht['ende']) # print('--------------------') if schicht['beginn'] == temp_beginn and schicht['ende'] == temp_ende: # Wenn sich mehrere Assistenten um die gleiche Schicht "bewerben", # können mehrere Schichten im selben Template stehen table_array[datakey][template_counter].append(schicht) schichten.remove(schicht) schicht_counter += 1 if schicht_counter == 0: table_array[datakey][template_counter] = [] template_counter += 1 print(schichten) print('---hurz-----') return splitted_templates, table_array
def handle_import(self, *args, **options): credentials_keys = ( 'user', 'password', 'host', 'port', 'database', ) credentials = { k: v for k, v in options.items() if k in credentials_keys } dry_run = options['dryrun'] export_skipped = options['export-skipped'] lp = int(options['limit-products']) lu = int(options['limit-users']) cat_id = int(options['category']) level = options['level'] owner = options['owner'] user_prg = 0 prod_prg = 0 user_total = 0 prod_total = 0 skipped_total = 0 slug_attempt = 0 product_desc_template = Template(self.PRODUCT_DESC_TEMPLATE) transaction.set_autocommit(False) try: self.stdout.write( "Connecting to {user}:*****@{host}:{port}/{database} ...". format(**credentials)) cnx = mysql.connector.connect(**credentials) c = cnx.cursor() del options['password'] except: self.stderr.write("Could not establish connection " + "to the rentalcompare database. Cause:") raise el_c = connection.cursor() try: DIVERS_CAT = Category.objects.get(id=cat_id) ELOUE_SITE = Site.objects.get(id=ELOUE_SITE_ID) propack = ProPackage.objects.create(name=self.PRO_PACKAGE_NAME, price=0) ir = ImportRecord.objects.create(origin=self.ORIGIN, file_name=self.FILENAME, imported_at=datetime.now()) imported_users_ids = self.get_imported_users_qs().values_list( 'original_id', flat=True) imported_products_ids = self.get_imported_products_qs( ).values_list('original_id', flat=True) filters = [] if level: filters.append("level='%s'" % level) if owner: filters.append("username='******'" % owner) where = ("where " + " ".join(filters)) if filters else "" c.execute("select count(*) from ob_users " + where) (user_count, ) = c.fetchone() user_count = min(user_count, lu) if user_count == 1: self.stdout.write("Importing user " + owner) elif user_count > 1: self.stdout.write("Importing %s users (type=%s)" % ( user_count, level if level else "*", )) else: raise Exception("No users correspond to your criteria") c.execute( "select * from ob_users " + where + " order by registered desc limit %s", (lu, )) RcUser = self.get_user_type(c.column_names) chunk = c.fetchmany(size=self.USERS_CHUNK_SIZE) username_counts = {} while len(chunk) > 0: for rc_user in imap(RcUser._make, chunk): user_prg = user_prg + 1 # if rc_user.id in imported_users_ids: # continue email_exists = Patron.objects.exists(email=rc_user.email) mess = "Importing user %5s out of %5s: %-50s" % \ (user_prg, user_count, ("reusing " if email_exists else "") + rc_user.username, ) self.stdout.write(mess, ending='\r') if not rc_user.email: # TODO do not skip w/o emails self.skip_user(rc_user, "email missing") continue if not rc_user.email: # TODO do not skip w/o emails self.skip_user(rc_user, "email missing") continue # PRO: # Nom entrprise company # Email email # Nom client # Username username # is_prof=true # # tel, phonenumber # addr # site # logo entrepr # desc entrepr #general_email ? u = { 'username': rc_user.username[:30], 'password': rc_user.password, 'email': rc_user.email, 'first_name': rc_user.display_name[:30], 'last_name': rc_user.lastname[:30], 'url': "http://%s" % rc_user.website if rc_user.website is not None else "", 'about': rc_user.about_me, 'import_record': ir, 'original_id': rc_user.id, 'avatar': rc_user.logo, # '': , } # addresse(s) if rc_user.level == "vendor": if rc_user.phonenumber is None: self.skip_user(rc_user, "pro with no phone") continue if not rc_user.has_address: self.skip_user(rc_user, "pro with no address") continue # pro-specific fields u.update({ 'company_name': rc_user.company[:50], 'is_professional': True, }) elif rc_user.level == "user": pass # if email_exists: # # TODO do not skip existing emails # self.skip_user(rc_user, "email exists") # continue # TODO handle unallowed characters if not email_exists: username_counts[rc_user.username] = 0 username_base = rc_user.username if len( rc_user.username) <= 27 else rc_user.username[:27] new_username = rc_user.username[:30] while Patron.objects.exists(username=new_username): username_counts[ rc_user.username] = username_counts[ rc_user.username] + 1 new_username = username_base + '_' + str( username_counts[rc_user.username]) u['username'] = new_username user = Patron(**u) user.init_slug() user.slug = user.slug[:50] slug_base = user.slug if len( user.slug) <= 47 else user.slug[:47] slug_attempt = 0 while Patron.objects.exists(slug=user.slug): # TODO generate new slug properly slug_attempt = slug_attempt + 1 user.slug = slug_base + "-" + str(slug_attempt) else: user = Patron.objects.get(email=rc_user.email) if rc_user.id not in imported_users_ids: if rc_user.phonenumber is not None: user.default_number = PhoneNumber( patron=user, number=rc_user.phonenumber, kind=PHONE_TYPES.OTHER) user.save() # user address if rc_user.has_address: # TODO refactor condition addr = rc_user.make_address(user) addr.save() user.default_address = addr user.save() if rc_user.level == "vendor": # boutique(s) # TODO refactor into User.build_boutique if rc_user.id not in imported_users_ids: agency = ProAgency.objects.create( patron=user, name=rc_user.company, phone_number=user.default_number, address1=addr.address1, address2=addr.address2, zipcode=addr.zipcode, city=addr.city, state=addr.state, country=addr.country) Subscription.objects.create(patron=user, propackage=propack) else: agency = ProAgency.objects.filter( patron=user).first() # products c.execute( "select count(*) from ob_products where vendor_id=%(user_id)s limit %(quantity)s;", { 'user_id': rc_user.id, 'quantity': lp }) (prod_count, ) = c.fetchone() prod_count = min(prod_count, lp) c.execute( "select * from ob_products where vendor_id=%(user_id)s order by date_lastaction desc limit %(quantity)s;", { 'user_id': rc_user.id, 'quantity': lp }) RcProduct = self.get_product_type(c.column_names) class RcPreparedProduct(): @classmethod def _make(clazz, iterable): res = RcProduct._make(iterable) res = res._replace(tags=', '.join( sorted( list( set(tag.strip() for tag in res.tags.split(',') if tag))))) return res prod_chunk = c.fetchmany( size=min(self.PRODUCTS_CHUNK_SIZE, lp)) products = [] prices = [] pictures = [] prod_cat = [] prod_prg = 0 prod_skipped = 0 while (len(prod_chunk) > 0): # prepare products and related objects for bulk save el_c.execute( "select nextval('products_product_id_seq')" + " from generate_series(1,%(prod_count)s)", {'prod_count': len(prod_chunk)}) for (rc_product, (alloc_id, )) in izip( imap(RcPreparedProduct._make, prod_chunk), el_c): if rc_product.id in imported_products_ids: prod_skipped = prod_skipped + 1 continue p = { "id": alloc_id, #owner "owner": user, # desc/summary "summary": rc_product.name, "description": product_desc_template\ .render(Context(rc_product._asdict())).strip(), #TODO Add all attributes # TODO caution "deposit_amount": 0, # currency "currency": rc_user.currency, #TODO handle 0 # addresse = "address": user.default_address, # phone = "phone": user.default_number, # qty "quantity": rc_product.qty if rc_product.qty is not None else 0, # category "category": DIVERS_CAT, #TODO add real category, "import_record": ir, "original_id": rc_product.id, "created_at":datetime.combine(rc_product.date_added, datetime_orig.time.min), } product = Product(**p) product.prepare_for_save() products.append(product) prod_cat.append( Product2Category(product=product, category=DIVERS_CAT, site=ELOUE_SITE)) if rc_product.price: prices.append( Price(product_id=alloc_id, amount=rc_product.price, currency=rc_user.currency, unit=UNIT.DAY)) if rc_product.price_weekly: prices.append( Price(product_id=alloc_id, amount=rc_product.price_weekly, currency=rc_user.currency, unit=UNIT.WEEK)) if rc_product.primary_photo: pictures.append( Picture(product_id=alloc_id, image=rc_product.primary_photo, created_at=datetime.now())) # bulk save products and related objects Product.objects.bulk_create(products) Product2Category.objects.bulk_create(prod_cat) ELOUE_SITE.products.add(*products) agency.products.add(*products) Price.objects.bulk_create(prices) Picture.objects.bulk_create(pictures) # get next chunk of products prod_prg = prod_prg + len(prod_chunk) skipped_total = skipped_total + prod_skipped prod_chunk = c.fetchmany( size=min(self.PRODUCTS_CHUNK_SIZE, lp)) products = [] prod_cat = [] prices = [] pictures = [] self.stdout.write( "\rImporting products for user %s: %s / %s (%s skipped)" % ( rc_user.username, prod_prg, prod_count, prod_skipped, ), ending='\r') prod_total = prod_total + prod_prg ELOUE_SITE.patrons.add(user) ir.patrons.add(user) user_total = user_total + 1 chunk = c.fetchmany(size=self.USERS_CHUNK_SIZE) users = [] self.stdout.write("\n") self.stdout.write("\rTotal users imported: %s" % (user_total, ), ending='\n') self.stdout.write("\rTotal products imported: %s" % (prod_total - skipped_total, ), ending='\n') self.stdout.write("\rTotal products skipped: %s" % (skipped_total, ), ending='\n') if dry_run: self.stdout.write( self.style.NOTICE("Dry run was enabled, rolling back."), ending='\n') transaction.rollback() else: self.stdout.write("Committing...", ending='\n') transaction.commit() c.close() cnx.close() except: transaction.rollback() self.stderr.write("\nGot an error, rolling back. Cause:", ending='\n') raise self.stdout.write("Import done.", ending='\n') if export_skipped: import json def date_handler(obj): return obj.isoformat() if hasattr(obj, 'isoformat') else obj self.stdout.write("Saving skipped objects...", ending='\n') f = open("skipped_users.json", "w") json.dump(self.skipped_users, f, default=date_handler, indent=1) f.close() f = open("skipped_products.json", "w") json.dump(self.skipped_products, f, default=date_handler, indent=1) f.close() f = open("skipped_logos.json", "w") json.dump(self.skipped_logos, f, default=date_handler, indent=1) f.close() self.stdout.write("Done.", ending='\n')
def save(self, *args, **kwargs): self.start_datetime = datetime.combine(self.date, self.start_time) self.end_datetime = self.start_datetime + dt.timedelta( hours=self.duration) super().save(*args, **kwargs)
def display_date(date, format='%Y-%m-%d'): return display_time(make_aware(datetime.combine(date, time())), format)
def panel_day(request, year, month, day): year=int(year) month=int(month) day=int(day) events_set = Event.objects.filter(datetime_point__year=year, datetime_point__month=month, datetime_point__day=day).order_by('datetime_point') events = [event for event in events_set] group_time = defaultdict(timedelta) duration_event_list = [] dayDuration = timedelta() if is_today(year, month, day): events.append(breakpoint()) markNow = datetime.now() else: markNow = None next_date = date(year, month, day) + timedelta(days=1) next_datetime = datetime.combine(next_date, datetime.min.time()) events.append(breakpoint(next_datetime)) if len(events) > 1: for i,event in enumerate(events[0:len(events)-1]): event.duration = events[i+1].datetime_point - event.datetime_point # correct events followed by timeout if events[i+1].window_class == 'INACTIVE' and events[i+1].name == 'TIMEOUT': event.duration -= timedelta(minutes=15) # correct infinite event (assuming 2h and more to be 15minutes task) if event.duration.total_seconds() > 2*60*60: event.duration = timedelta(minutes=15) event.duration = chop_microseconds(event.duration) # add event to display list if event.window_class != 'INACTIVE': if event.duration > timedelta(seconds=10): group_time[event.window_class] += event.duration event.id_hash = hashlib.sha1(str(event.__hash__()).encode()).hexdigest() event.end = event.datetime_point + event.duration dayDuration += event.duration duration_event_list.append(event) dayDuration = chop_microseconds(dayDuration) class_list = [k for k in group_time] svg_legend = printsvg_legend() svgs, colors = printsvg(duration_event_list, class_list, markNow) group_sorted = sorted([Group(group_time[k],k,colors[k]) for k in group_time], key=lambda g: g.time, reverse=True) for event in duration_event_list: event.datetime_point = event.datetime_point.strftime("%X") event.end = event.end.strftime("%X") event.color = colors[event.window_class] select = [''] + sorted([key for key in class_list]) if duration_event_list: dayStart = duration_event_list[0].datetime_point dayEnd = duration_event_list[-1].end else: dayStart = "no data" dayEnd = "no data" return render(request, 'panel.html', { 'year': year, 'month': month, 'day': day, 'event_list': duration_event_list, 'group_sorted': group_sorted, 'svgs': svgs, 'svg_legend': svg_legend, 'dayStart': dayStart, 'dayEnd': dayEnd, 'dayDuration': dayDuration, 'colors': svgcolors, 'select': select })