def get_teleconsultations(request): """ :param request: :return: a list of opened teleconsultation for device task-groups """ today = datetime.now().date() tomorrow = today + timedelta(1) today_start = datetime.combine(today, time()) today_end = datetime.combine(tomorrow, time()) today_start = datetime.combine(today, time()) logging.error("Taskgroup from token: %s" % request.accesstoken.taskgroup) teleconsultations = Teleconsultation.objects.filter(task_group=request.taskgroup, updated__lte=today_end, updated__gte=today_start) teleconsultation_list = [] for teleconsultation in teleconsultations: teleconsultation_list.append(teleconsultation.json_dict) result = { "teleconsultations": teleconsultation_list } return HttpResponse(json.dumps({'success': True, 'data': result}), content_type="application/json")
def setTime(self, time): if type(time) == str: self.xml["environment"]["datetime"] = datetime.combine(self.xml["environment"]["datetime"].date(), dateutil.parser.parse(time).time()) elif isinstance(time, datetime.time) : self.xml["environment"]["datetime"] = datetime.combine(self.xml["environment"]["datetime"].date(), time) else: raise dumpManagerException("(dumpManager) setTime, the time must be an instance of datetime.time")
def map_todays_inserted_domains_from_articles(domain_analysis_outfile): re_domain = re.compile("http.*//([^<]*?)/.*") # Match between // and the next / domains = {} today = datetime.today() date_start = datetime.combine(today.date(), time (0, 0, 0, 0)) date_end = datetime.combine(date(today.year, today.month, today.day + 1), time (0, 0, 0, 0)) articles_inserted_today = articles.find({ 'procd': { '$gte': date_start, '$lt': date_end }}) for article in articles_inserted_today: domain = re_domain.search(article['url']).group(1) if (domains.has_key(domain)): domains[domain] = domains[domain] + 1 else: domains[domain] = 1 # TODO: Figure out if utf-8 is needed or ASCII is OK? outfile = codecs.open(domain_analysis_outfile, 'a+', encoding='utf-8') # Print tuples to a file for key, value in domains.items(): outfile.write(key + '\t' + str(value) + '\n') outfile.close()
def curation_email_and_file(outfilepath): # Delete previous curation file if (os.path.isfile(outfilepath)): os.unlink(outfilepath) outfile = open(outfilepath, 'a') errormessages = "" for user in users.find(): #body = "" body = "<b>Curation request for:</b>" + user['e'] + "<br><br>" # See if any recommendations were made today today = datetime.today() date_start = datetime.combine(today.date(), time (0, 0, 0, 0)) # Not used: See if any recommendations made in the last 3 days #date_start = today + relativedelta(days =- 3) date_end = datetime.combine(date(today.year, today.month, today.day + 1), time (0, 0, 0, 0)) # Find news articles recommended today and send them recommended_articles_today = recommended_articles.find({ 'uid': user['_id'], 'rt': { '$gte': date_start, '$lt': date_end }}) if (recommended_articles_today.count() == 0): print "ERROR: No new article recommendations" errormessages += "ERROR: No new article recommendations for user: "******"<br>" #body += "No new article recommendations today!" continue # Pull recommended articles and put in body for recommended_article in recommended_articles_today: article_id = recommended_article['aid'] match_articles = articles.find({ 'c': article_id }) for article_match in match_articles: body += '<a href="' + article_match['url'] + '">' + article_match['t'] + '</a><br>' outfile.write('{0}\t{1}\t{2}\n'.format(str(0), user['e'], article_match['url'])) print "Sent " + str(recommended_articles_today.count()) + " news articles for curation. Email: " + user['e'] # Send via SendGrid # make a secure connection to SendGrid s = sendgrid.Sendgrid(SENDMAIL_EMAIL, SENDMAIL_PASS, secure=True) message = sendgrid.Message(SENDMAIL_EMAIL, "Curation Request", "plaintext message body", body) message.add_to(SENDMAIL_EMAIL) s.web.send(message) #s.smtp.send(message) # If there are any error messages, send them if (errormessages is not ""): senderror(SENDMAIL_EMAIL, errormessages) outfile.close()
def main(): site_id_api="api/prov/v1/sites/list" domain_name_api="api/prov/v1/sites/status" visits_api="api/visits/v1" # get yesterday and today in epoch unix timestamp and add millisconds to it yesterdayMidnight = "%s" % ((str( totimestamp(datetime.combine((date.today() - timedelta(days=1)), time.min)) ))).split('.')[0] + "000" todayMidnight = "%s" % ((str( totimestamp(datetime.combine(date.today(), time.min)) ))) .split('.')[0] + "000" #yesterdayMidnight = "%s" % ((str( totimestamp(datetime.combine((date.today() - timedelta(days=2)), time.min)) ))).split('.')[0] + "000" # day before yesterday #todayMidnight = "%s" % ((str( totimestamp(datetime.combine((date.today() - timedelta(days=1)), time.min)) ))) .split('.')[0] + "000" # day before yesterday data = get_curl(site_id_api , "") #print json.dumps(data, indent=4, separators=(',', ': ')) #debug sites_num=len(data['sites']) site_id_array = [None] * sites_num for x in range(0,sites_num): site_id_array[x] = data['sites'][x]['site_id'] page_size=100 #max the api will return :'( site_dict={} #collect domain name from site_id numbers for site_id_num in site_id_array: data=get_curl(domain_name_api, "site_id=%s" % site_id_num) #print json.dumps(data, indent=4, separators=(',', ': ')) #debug site_dict[site_id_num]=data['domain'] #get stats for each site for key in site_dict: page_num=0 visit_num_total = 0 while True: site=key data=get_curl( visits_api, "site_id=%s&time_range=custom&start=%s&end=%s&page_size=%s&page_num=%s&security=&country=&ip=&visit_id=&list_live_visits=" % (key, yesterdayMidnight, todayMidnight, page_size, page_num)) if (len(data["visits"]) == 0): break page_num= page_num + 1 visits_num=len(data['visits']) for visit in range(0, visits_num): visit_num_total = visit_num_total + 1 #visits = json.dumps(data["visits"][visit], sort_keys=True, indent=1, separators=(',', ': ')) visits = json.dumps(data["visits"][visit], sort_keys=True, separators=(',', ': ')) #visits = "" json_string="{\"_time_range\":\"%s\",\"site\":\"%s\",\"site_id\":\"%s\",\"visit_num\":\"%s\",\"visit\":\"%s\"}" % ( yesterdayMidnight + ":" + todayMidnight ,site_dict[site],site, visit_num_total, visits) print json_string
def show_webcast(self): from datetime import date, datetime, time, timedelta """Returns True the current time is 15 minutes before the start time and an hour after the finish time.""" st = datetime.combine(self.event_date, self.start_time) - timedelta(minutes=15) ft = datetime.combine(self.event_date, self.finish_time) + timedelta(minutes=60) ct = datetime.now() if self.is_expired: return False elif self.has_webcast == False: return False else: while (ct > st): if ct > ft: break return True
def http_error_422(self, req, fp, code, msg, hdrs): s = fp.read().decode(encoding='UTF-8') data = json.loads(s) logging.info('Received HTTP Error 422') logging.debug(data) if 'Failed to parse date' in data['reason']: logging.error(req.get_full_url()) logging.error(data) return if 'Requested date range is invalid for this system' in data['reason']: logging.error(req.get_full_url()) logging.error(data) return startAt = self.dtt.datetimeify('start_at',data['start_at']) lastInt = self.dtt.datetimeify('last_interval', data['last_interval']) if startAt > lastInt: endAt = self.dtt.datetimeify('end_at',data['end_at']) startAt = dt.combine(endAt.date(),datetime.time()) s,n,pa,pr,q,f = p.urlparse(req.get_full_url()) params = dict(p.parse_qsl(q)) params['start_at'] = self.dtt.stringify('start_at', startAt.timestamp()) qstring = p.urlencode(params) url = p.urlunparse((s,n,pa,pr,qstring,f)) return r.build_opener(self).open(url)
def horarioUsuario(User): horas = parametros["horas"] diasSemana = parametros["diasSemana"] horario = dict() for d in diasSemana: for h in horas: horario[(d, h)] = '' try: estudiante = Estudiante.objects.get(user = User) gruposEstudiante = Grupo.objects.filter(idEstudiante = estudiante) except: return {} for grupoE in gruposEstudiante: horariosGrupo = Horario.objects.filter(idCurso = grupoE.idCurso) for h in horariosGrupo: horaInicio = h.horaInicio horaFin = h.horaFin horaTmp = horaInicio while horaTmp < horaFin: if horaTmp.strftime("%H:%M") in horas and h.dia in diasSemana: horario[(h.dia, horaTmp.strftime("%H:%M"))] = h.idCurso.nombre horaTmp = (datetime.combine(date.today(), horaTmp) + timedelta(hours=1)).time() return horario """
def city_pace_count_rest(): current_server_time = datetime.utcnow() #current_client_date = timezone(tz).fromutc(current_server_time) if City_Pace.objects.all().order_by('city_pace_date').last(): last_date_counted = City_Pace.objects.all().order_by('city_pace_date').last().city_pace_date mytime = datetime.strptime('2130','%H%M').time() last_date_counted = datetime.combine(last_date_counted, mytime) else: #aware - абсолютное время, так как берётся из БД last_date_counted = Measurement.objects.all().order_by('measurement_date').first().measurement_date current_server_time = timezone(tz).fromutc(current_server_time) #logger.info(last_date_counted) #logger.info(current_client_date) if current_server_time.date() != last_date_counted.date(): for a_date in range((current_server_time - last_date_counted).days): new_pace = 0. logger.info(last_date_counted + timedelta(days = a_date + 1)) for a_bin in Bin.objects.all(): new_date = last_date_counted + timedelta(days = a_date + 1) new_date = timezone('UTC').fromutc(new_date) logger.info(new_date) new_pace += a_bin.bin_generate_volume_pace_of_date(new_date) #logger.info(a_bin.bin_adress) #logger.info(a_bin.bin_generate_volume_pace_of_date(last_date_counted + timedelta(days = a_date + 1))) logger.info(float("{0:.2f}".format(new_pace * 24 / 1000))) new_city_pace = City_Pace(city_pace_date = last_date_counted + timedelta(days = a_date + 1), city_pace_value = new_pace * 24 / 1000) new_city_pace.save()
def api(request): try: metric_name = None metric_value = None for k,v in request.GET.items(): if k == 'stream': q = v else: metric_name = k metric_value = v keyword_model = Keyword.objects.filter(name=q) if not metric_name == None and not metric_value == None: metric_model = Metric.objects.filter(name=metric_name, value=metric_value) dataset = Datapoint.objects.filter(keyword=keyword_model, metric=metric_model).order_by('time') else: dataset = Datapoint.objects.filter(keyword=keyword_model, metric=None).order_by('time') from datetime import date, time, datetime, timedelta dataset_dict = {dp.time: dp.count for dp in dataset} resolution = timedelta(hours=1) t0 = datetime.combine(date.today() - timedelta(days=90), time()) times = (t0 + resolution * i for i in range(24 * 90)) response = [[epoch(t), dataset_dict.get(t, 0)] for t in times] return HttpResponse(json.dumps(response), mimetype="application/json") except Exception, e: return HttpResponse(str(e))
def _parseFlightLegDetails(self, day, legDetails): ''' Return a FlightLegLocation with parsed leg location information ''' f = FlightLegLocation() # Get airport code departure_airport = FindByTagClass(legDetails, 'td', 'routingDetailsStops') f.airport = re.findall('[A-Z]{3}', str(departure_airport))[0] dlog("Airport Code: " + f.airport) # Cannot get the find method with regex working # f.airport = departure_airport.find(text=re.compile('[A-Z]{3}')) # Get timezone f.tz = airport_timezone_map[f.airport] # Get time segmentTime = FindByTagClass(legDetails, 'td', 'routingDetailsTimes', get_text=True) # Create time() object flight_time = time(*time_module.strptime(segmentTime.strip().rstrip("Next Day").strip(), '%I:%M %p')[3:5]) dlog("Time: " + str(flight_time)) f.dt = f.tz.localize( datetime.combine(day, flight_time), is_dst=None) f.dt_utc = f.dt.astimezone(utc) # Formatted datetime f.dt_utc_formatted = DateTimeToString(f.dt_utc) f.dt_formatted = DateTimeToString(f.dt) return f
def start_dt(dateobject): if type(dateobject) == datetime: if hasattr (dateobject,'tzinfo') and dateobject.tzinfo: return dateobject else: return source.site.tz.localize(dateobject) if not dateobject: return None return source.site.tz.localize(datetime.combine(dateobject, time(0)))
def forwards(self, orm): from datetime import datetime for course_mode in orm.CourseMode.objects.all(): if course_mode.expiration_date is None: course_mode.expiration_datetime = None course_mode.save() else: course_mode.expiration_datetime = datetime.combine(course_mode.expiration_date, datetime.min.time()) course_mode.save()
def cal_demo(queryset): cal = Calendar() cal.add('version', '2.0') cal.add('prodid', '-//V and A upcoming events//www.vam.ac.uk.com/whatson/') cal.add('X-WR-CALNAME','V and A Events Calendar' ) # lt = LocalTimezone() # we append the local timezone to each time so that icalendar will convert # to UTC in the output lt = pytz.timezone('Europe/London') for ent in queryset: event = Event() event.add('summary', ent['event_name']) event.add('dtstart', datetime.combine(ent['event_date'],ent['start_time']).replace(tzinfo=lt)) event.add('dtend', datetime.combine(ent['stop_date'],ent['stop_time']).replace(tzinfo=lt)) event.add('dtstamp', ent['updated_on'].replace(tzinfo=lt)) event['uid'] = ent.pk # should probably use a better guid than just the PK event.add('description', ent['description']) cal.add_component(event) return cal.to_ical()
def potencias_historicas(): from datetime import date, time, datetime, timedelta d = datetime.combine(date.today(), time(0, 0, 0)) next = datetime.today() + timedelta(days=1) data = [] while d < next: data.append([d, randrange(1,100)]) d += timedelta(minutes=randrange(1,60)) return dumps(dict(data=data))
def unocc_fan_operation(self, dx_result): """If the AHU/RTU is operating during unoccupied periods inform the building operator. """ avg_duct_stcpr = 0 percent_on = 0 fanstat_on = [(fan[0].hour, fan[1]) for fan in self.fanstat_values if int(fan[1]) == 1] fanstat = [(fan[0].hour, fan[1]) for fan in self.fanstat_values] hourly_counter = [] for counter in range(24): fan_on_count = [fan_status_time[1] for fan_status_time in fanstat_on if fan_status_time[0] == counter] fan_count = [fan_status_time[1] for fan_status_time in fanstat if fan_status_time[0] == counter] if len(fan_count): hourly_counter.append(fan_on_count.count(1)/len(fan_count)*100) else: hourly_counter.append(0) if self.sched_time: if self.fanstat_values: percent_on = (len(fanstat_on)/len(self.fanstat_values)) * 100.0 if self.stcpr_arr: avg_duct_stcpr = mean(self.stcpr_arr) if percent_on > self.unocc_time_threshold: msg = 'Supply fan is on during unoccupied times.' dx_msg = 63.1 else: if avg_duct_stcpr < self.unocc_stp_threshold: msg = 'No problems detected for schedule diagnostic.' dx_msg = 60.0 else: msg = ('Fan status show the fan is off but the duct static ' 'pressure is high, check the functionality of the ' 'pressure sensor.') dx_msg = 64.2 else: msg = 'No problems detected for schedule diagnostic.' dx_msg = 60.0 if dx_msg != 64.2: for _hour in range(24): push_time = self.timestamp[0].date() push_time = datetime.combine(push_time, datetime.min.time()) push_time = push_time.replace(hour=_hour) dx_table = {SCHED_RCX + DX: 60.0} if hourly_counter[_hour] > self.unocc_time_threshold: dx_table = {SCHED_RCX + DX: dx_msg} table_key = create_table_key(self.sched_file_name_id, push_time) dx_result.insert_table_row(table_key, dx_table) else: push_time = self.timestamp[0].date() table_key = create_table_key(self.sched_file_name_id, push_time) dx_result.insert_table_row(table_key, {SCHED_RCX + DX: dx_msg}) dx_result.log(msg, logging.INFO) return dx_result
def book(request): json_data = json.dumps({"HTTPRESPONSE":0}) if request.method == "POST": room = Room.objects.get(pk=request.POST['room_id']) date = datetime.strptime(request.POST['date'], '%Y-%m-%d') hours = json.loads(request.POST['hours']) delta = timedelta(hours = 1) error = False try: with transaction.atomic(): for h in hours: begin = datetime.strptime(h, "%H:%M").time() end = (datetime.combine(dt.today(), begin) + delta).time() reservation = Reservation( user=request.user, room=room, date=date, begin_time=begin, end_time=end ) try: reservation.clean() except ValidationError as e: message = begin.__str__()[:5] + "-" + end.__str__()[:5] + " is not available" json_data = json.dumps({"HTTPRESPONSE":0, "ERROR": message}) error = True break for t in room.freeterm_set.filter(date=date): if t.begin_time <= begin and t.end_time >= end: break left = FreeTerm( room=room, date=date, begin_time=t.begin_time, end_time=begin ) right = FreeTerm( room=room, date=date, begin_time=end, end_time=t.end_time ) t.delete() if left.begin_time < left.end_time: left.save() if right.begin_time < right.end_time: right.save() reservation.save() if not error: json_data = json.dumps({"HTTPRESPONSE":1}) except IntegrityError: messages.error(request, 'Something went wrong') return HttpResponse(json_data, mimetype="application/json")
def generate_pq_for_day(a_date, step=None): ''' Genera los 96 valores de energía ''' if not step: step = timedelta(minutes=15) a_date = datetime.combine(date.today(), time(0, 0, 0)) limit = a_date + timedelta(days=1) maketuple = lambda d: (d.isoformat(), randrange(1, 100), randrange(1, 50), ) return [ maketuple(d) for d in dateiter(a_date, limit, step)]
def _get_job_text(pub_date, mode = "default"): from tourprom.job.models import BulletinVacancy, Resume vacancies = BulletinVacancy.objects.filter(date=pub_date) try: prev_bulletin = Bulletin.objects.filter(date__lt=pub_date).order_by('-date')[0] resumes = Resume.objects.filter(date_changed__lt=datetime.combine(pub_date, time()), date_changed__gt=datetime.combine(prev_bulletin.date, time()), is_published=True) except IndexError: resumes = [] return render_to_string('bulletin/job_messages.html', {'vacancies': vacancies, 'resumes': resumes, 'mode': mode, 'site': Site.objects.get_current()})
def remaining_time(self): from datetime import datetime now = datetime.now() if self.expiration_date: exp = self.expiration_date exp = datetime.combine(exp, datetime.min.time()) d = exp - now return d.days else: return None
def apptsuccess(request): flag =True p_name = request.user.id p_user = User.objects.get(id=p_name) d_name = request.POST.get("Doctor_name", "") d_user = User.objects.get(id=d_name) medProblem = request.POST.get("Medical_problem", "") date_unicode = request.POST.get("date", "") time_unicode = request.POST.get("time1", "") if(p_name!=None and p_name!="" and d_name!=None and d_name!='' and medProblem!=None and medProblem!='' and date_unicode!=None and date_unicode!='' and time_unicode!=None and time_unicode!="" and parse_date(date_unicode) > datetime.now()): time_list=[] db_date_list=[] timedelta_list=[] date_list=[] date = datetime.strptime(date_unicode, "%Y-%m-%d") time = datetime.strptime(time_unicode, "%H:%M") calendar_date = datetime.strptime(date_unicode+" " +time_unicode, "%Y-%m-%d %H:%M") for a in User.objects.raw('SELECT * FROM login_appt;'): if(a.doctor_id == long(d_name)): time_list.append(a.time) date_list.append(a.date) db_date_list.append(datetime.combine(a.date,a.time)) if(calendar_date in db_date_list): flag=False else: for d in db_date_list: time_added = d + timedelta(minutes=15) if(calendar_date<time_added and calendar_date>d): flag=False break else: flag=True continue if flag==False: doctor_list=[] for doctor in User.objects.raw('SELECT * FROM auth_user a join login_userrole b on a.id=b.user_id where b.role="doctor";'): doctor_list.append(doctor) return render_to_response('patient/appointment.html',{'user': request.user, 'doctor': doctor_list, 'message':'Sorry, There is a time clash, please select a different time.'}) else: d = Appt.objects.create(patient=p_user,doctor=d_user,medical_problem=medProblem,date=date,time=time) d.save() return render_to_response('patient/success.html',{'user': request.user}) else: doctor_list=[] for doctor in User.objects.raw('SELECT * FROM auth_user a join login_userrole b on a.id=b.user_id where b.role="doctor";'): doctor_list.append(doctor) return render_to_response('patient/appointment.html',{'user': request.user, 'doctor': doctor_list, 'message':'Either the information you have filled is incorrect or empty. Please check.'}) d = Appt.objects.create(patient=p_user,doctor=d_user,medical_problem=medProblem,date=date,time=time) d.save() return render_to_response('patient/success.html',{'user': request.user})
def diff_dates(self, date1, date2): try: try: d1 = datetime.strptime(date1, '%d/%m/%Y') except: d1 = datetime.combine(date1, datetime.min.time()) d2 = datetime.strptime(date2, '%d/%m/%Y') diff = abs((d1 - d2).days) return str(diff) except: return "diff_dates_error"
def _get_photogallery_text(pub_date, mode = "default"): weekday = pub_date.weekday() if weekday == 0: ts = time(0,0) te = time(23,59) holidays = ChangedDate.objects.filter(date=pub_date,publish=False) if len(holidays) > 0: dt_s = datetime.combine(pub_date - timedelta(days=4), ts) else: dt_s = datetime.combine(pub_date - timedelta(days=3), ts) dt_e = datetime.combine(pub_date - timedelta(days=1), te) photos = PhotoGallery.objects.filter(date_added__lte=dt_e, date_added__gte=dt_s, gallery_type=2) photos_count = photos.count() else: ts = time(0,0) te = time(23,59) holidays = ChangedDate.objects.filter(date=pub_date,publish=False) if len(holidays) > 0: dt_s = datetime.combine(pub_date - timedelta(days=2), ts) else: dt_s = datetime.combine(pub_date - timedelta(days=1), ts) dt_e = datetime.combine(pub_date - timedelta(days=1), te) photos = PhotoGallery.objects.filter(date_added__lte=dt_e, date_added__gte=dt_s, gallery_type=2) photos_count = photos.count() return render_to_string('bulletin/photo_gallery_new.html', {'photos': photos, 'photos_count': photos_count, 'mode': mode, 'pub_date': pub_date, 'site': Site.objects.get_current()})
def test_animation(): from datetime import date,time,timedelta import datetime d = date(2013,11,17) t = time(8,36) start = datetime.combine(d,t) now = start t = time(9,52) end = datetime.combine(d,t) delta = timedelta(seconds=2) snapshots = [] while now < end: snapshot = QuakeSnapshot(now) print snapshot.get_url() snapshots.append(snapshot) now += delta import animation animation.write_animatedgif( snapshots, "hoge.gif" )
def __call__(self, data): ''' Params: - data: the data source to filter/process Returns: - False (always) because this filter does not remove bars from the stream ''' # Get time of current (from data source) bar dtime = datetime.combine(data.datetime.date(), self.p.endtime) data.datetime[0] = data.date2num(dtime) return False
def test_vencimiento_mas_de_10_dias(self): desde = TEMPORADA_ALTA[0] # 3 dias de baja hasta = TEMPORADA_ALTA[0] + timedelta(days=4) # 4 dias de alta reserva = ReservaFactory(desde=desde, hasta=hasta) midnight = time(0, 0, tzinfo=pytz.utc) reserva_datetime = combine(TEMPORADA_ALTA - timedelta(11), midnight) with freeze_time(reserva_datetime): # mas de 10 dias vence a las 24hs. reserva.calcular_vencimiento() self.assertEqual(reserva.fecha_vencimiento_reserva, reserva_datetime + timedelta(hours=24))
def _parseFlightStop(self, day, soup): flight_stop = FlightStop() stop_td = FindByTagClass(soup, "td", "routingDetailsStops") s = "".join(stop_td.findAll(text=True)) flight_stop.airport = re.findall("\(([A-Z]{3})\)", s)[0] flight_stop.tz = airport_timezone_map[flight_stop.airport] detail_td = FindByTagClass(soup, "td", "routingDetailsTimes") s = "".join(detail_td.findAll(text=True)).strip() flight_time = time(*time_module.strptime(s, "%I:%M %p")[3:5]) flight_stop.dt = flight_stop.tz.localize(datetime.combine(day, flight_time), is_dst=None) flight_stop.dt_utc = flight_stop.dt.astimezone(utc) return flight_stop
def determine_break_from_interview_time(time_period, interview_type): if interview_type != models.InterviewType.ON_SITE: return None weekday = time_period.start_time.weekday() if weekday != 4: # Friday return None tz_info = time_period.start_time.tzinfo start_of_break = dt_time(12, 0, tzinfo=tz_info) end_of_break = dt_time(13, 30, tzinfo=tz_info) date = time_period.start_time.date() start_of_break_dt = datetime.combine(date, start_of_break) end_of_break_dt = datetime.combine(date, end_of_break) break_time_period = TimePeriod( start_of_break_dt, end_of_break_dt, ) if time_period.contains(break_time_period): print "Adding break %s" % break_time_period return break_time_period return None
def datetime(obj): """Default JSON serializer.""" import calendar from datetime import date, datetime if isinstance(obj, datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() elif isinstance(obj, date): obj = datetime.combine(obj, datetime.min.time()) return int(calendar.timegm(obj.timetuple()))
def __add_date(start_time, interval, r_type): from datetime import datetime, date, time, timedelta import re start_time = map(int, start_time) interval = map(int, interval) t = datetime.combine(date(start_time[0], start_time[1], start_time[2]), time(start_time[3], start_time[4], start_time[5])) ad = timedelta(days=interval[0], hours=interval[1], minutes=interval[2], seconds=interval[3]) t += ad if r_type is tuple: return re.findall(re.compile(r'(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)'), t.strftime('%Y-%m-%d %H:%M:%S'))[0] elif r_type is str: return t.strftime('%Y-%m-%d %H:%M:%S')
def search(request): update_status(request) fromWhere_query = request.GET.get('fromWhere','') whereTo_query = request.GET.get('whereTo','') date_query = request.GET.get('date','') journeys = [] stations_fromWhere1 = [] stations_whereTo1 = [] schedule = [] dates = [] status = [] journeys1 = Journey.objects.all() for j in journeys1: stations_fromWhere = Station.objects.filter(journey = j, stationName__iexact = fromWhere_query) distance1_value = stations_fromWhere.values() stations_whereTo = Station.objects.filter(journey = j, stationName__iexact = whereTo_query) distance2_value = stations_whereTo.values() schedule_date = Schedule.objects.filter(journey_id = j, DepartureDate = date_query) if distance1_value.exists() and distance2_value.exists(): for station1 in distance1_value: distance1 = station1['distanceFromStart'] days1 = station1['daysFromStart'] hours1 = station1['hoursFromStart'] minutes1 = station1['minutesFromStart'] stop1 = station1['stopTime'] for station2 in distance2_value: distance2 = station2['distanceFromStart'] days2 = station2['daysFromStart'] hours2 = station2['hoursFromStart'] minutes2 = station2['minutesFromStart'] travel_time1 = timedelta(days=days1, hours=hours1, minutes=minutes1+stop1) travel_time2 = timedelta(days=days2, hours=hours2, minutes=minutes2) if distance1 < distance2 and schedule_date.exists(): schedule_date = Schedule.objects.get(journey_id = j, DepartureDate = date_query) departure_datetime = datetime.combine(schedule_date.DepartureDate, schedule_date.DepartureTime) departure = departure_datetime + travel_time1 arrival = departure_datetime + travel_time2 if departure < datetime.now(): status.append({ 'journey' : j, 'status' : 'Відправлено' }) else: status.append({ 'journey' : j, 'status' : '' }) journeys += Journey.objects.annotate(price = F('FullDistance') * 0 +(distance2-distance1)).filter(id__contains = j.id) stations_fromWhere1 += stations_fromWhere stations_whereTo1 += stations_whereTo schedule += Schedule.objects.filter(journey_id = j, DepartureDate = date_query) dates.append({'journey' : j, 'departure' : departure, 'arrival' : arrival}) context = {'journeys' : journeys, 'st_fromWhere' : stations_fromWhere1, 'st_whereTo' : stations_whereTo1, 'fromWhere' : fromWhere_query, 'whereTo' : whereTo_query, 'schedule' : schedule, 'date_journey' : date_query, 'dates' : dates, 'status' : status } return render(request, 'app/search.html', context)
import datetime today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) tomorrow = today + datetime.timedelta(days=1) print('Yesterday : ', yesterday) print('Today : ', today) print('Tomorrow : ', tomorrow) ### 8. Write a Python program to convert the date to datetime (midnight of the ### date) in Python from datetime import date from datetime import datetime dt = date.today() print(datetime.combine(dt, datetime.min.time())) ### 9. Write a Python program to print next 5 days starting from today. import datetime base = datetime.datetime.today() for x in range(0, 5): print(base + datetime.timedelta(days=x)) ### 10. Write a Python program to add 5 seconds with the current time import datetime x = datetime.datetime.now() y = x + datetime.timedelta(0, 5) print(x.time()) print(y.time())
def get(self): current_user = self.auth.get_user_by_session() cinema_id = current_user['cinema_id'] logging.debug(cinema_id) cinema1 = CinemaHall.get_by_id(cinema_id, parent=testing_key('default')) access = 'Cashier' if (current_user['manager']): access = 'Manager' if (current_user['admin']): access = 'Admin' dtime = datetime.now() d = timedelta(hours=5, minutes=30) dtime = d + dtime time = datetime.time(dtime) today = datetime.date(dtime) show = {} show[1] = datetime.combine(today, cinema1.show_time1) show[2] = datetime.combine(today, cinema1.show_time2) show[3] = datetime.combine(today, cinema1.show_time3) show[4] = datetime.combine(today, cinema1.show_time4) mins45 = timedelta(minutes=45) mins30 = timedelta(minutes=30) mins15 = timedelta(minutes=15) show[1] += mins45 show[2] += mins45 show[3] += mins45 show[4] += mins45 if (dtime < show[1]): s = 1 elif (dtime < show[2]): s = 2 elif (dtime < show[3]): s = 3 elif (dtime < show[4]): s = 4 else: s = 0 self.display_message('No more shows for today. Click <a href="/"> here </a> to go back!') return time_diff = show[s] - mins15 - dtime time_in_s = time_diff.total_seconds() time_in_millis = time_in_s * 1000 if (time_in_millis <= 0): time_in_millis = 1 logging.debug("Show " + str(s) + " " + str(show[s])) limit = [0, 0, 0, 0, 0, 0] show[s] = show[s] - mins15 limit[0] = show[s].year limit[1] = show[s].month limit[2] = show[s].day limit[3] = show[s].hour limit[4] = show[s].minute limit[5] = show[s].second show[s] = show[s] + mins15 logging.debug("**************" + str(show[s].month)) autosubmit = datetime.time(show[s]) showtime = datetime.time(show[s] - mins45) show = s types = ['box', 'balcony', 'odc', 'firstclass', ] seats = {} seats1 = {} for type in types: s = Seat.gql('WHERE cinema_id=:1 AND catagory=:2', cinema1.key().id(), type).get() seats[type] = s.number seats1[type] = 0 dtime = datetime.now() d = timedelta(hours=5, minutes=30) dtime = d + dtime today = datetime.date(dtime) #check whether the show record exists: logging.debug(str(show) + " " + str(today) + " " + str(cinema_id)) showrecord = ShowRecord.gql('WHERE show=:1 AND date=:2 AND cinema_id=:3', show, today, cinema_id).get() logging.debug(showrecord) if (showrecord): logging.debug(str(showrecord.key().id())) types = ['box_full', 'balcony_full', 'balcony_half', 'balcony_service', 'balcony_complimentary', 'odc_full', 'odc_half', 'odc_service', 'odc_complimentary', 'firstclass_full', 'firstclass_half', 'firstclass_service', 'firstclass_complimentary', ] notickets = 0 for type in types: ticketsale = TicketSale.gql('WHERE show_record_id=:1 AND ticket_type=:2', showrecord.key().id(), type).get() seats1[type.split('_')[0]] += ticketsale.sales logging.debug(type.split('_')[0] + str(seats[type.split('_')[0]])) film = "Film" reel = "Reel" cinema = cinema1.name place = cinema1.place template_values = { 'seats1': seats1, 'seats': seats, 'limit': limit, 'cinema_id': cinema_id, # 'run': run, 'film': film, 'reel': reel, # 'day': day, # 'date': date, 'cinema': cinema, 'place': place, # 'code_no' : code_no, # 'grade' : grade, 'show': show, 'autosubmit': autosubmit, 'time_in_millis': time_in_millis, 'access': access, 'showtime': showtime, } self.render_template('dataentry.html', template_values)
def plot_prediction_error(self) -> None: if self.config.graph['prediction_error']: times = [] prediction_data = {} arrays = {} if self.config.graph['use_x_date']: min_t = datetime(2200, 12, 31, 23, 59, 59) max_t = datetime(1970, 1, 1, 0, 0, 0) else: min_t = 10000000 max_t = 0 magnitude = 0.0 x_window = (0, 0) for lab in self.config.labs: lab_date = lab['date'] lab_value = lab['values'] plot_start = datetime.combine(self.config.model['start_date'], time(0, 0, 0)) if self.config.graph['use_x_date']: lab_time = lab_date min_t = min(min_t, lab_time) max_t = max(max_t, lab_time) # if lab_time < min_t: # min_t = lab_time # if lab_time > max_t: # max_t = lab_time x_window = (min_t - timedelta(days=7), max_t + timedelta(days=7)) else: lab_time = (lab_date - plot_start).total_seconds() / self.config.graph['units'].total_seconds() min_t = min(min_t, lab_time) max_t = max(max_t, lab_time) x_window = (max(min_t - 7, 0), min(max_t + 7, self.duration)) times.append(lab_time) for drug_key, lab_val in lab_value.items(): predicted = self.model.get_blood_level_at_timepoint(drug_key, lab_date) predicted = predicted[0] * predicted[1] if drug_key not in prediction_data: prediction_data[drug_key] = [] # print(f"{predicted} -> {lab_val}") val = ((lab_val - predicted) / lab_val) * 100 if val >= 0: magnitude = max(magnitude, val) else: magnitude = max(magnitude, -val) prediction_data[drug_key].append(val) for drug_key, data in prediction_data.items(): arrays[drug_key] = (np.array(data), np.array(data), np.array(data)) if self.config.graph['use_x_date']: duration_labs = math.ceil((max_t - min_t + timedelta(days=14)).total_seconds() / (3600 * 24)) else: duration_labs = max_t - min_t + 14 delta = 7 tick_count = math.floor(duration_labs / delta) while tick_count > 12: delta *= 2 tick_count = math.floor(duration_labs / delta) plot_drugs(data=(np.array(times), arrays), x_window=x_window, y_window=(-magnitude * 1.2, magnitude * 1.2), x_ticks=delta, x_label=self.config.graph['x_label'], y_label="Deviation of estimation (%)", title="Prediction accuracy", plot_markers=True, plot_dates=self.config.graph['use_x_date'], )
def get(self): current_user = self.auth.get_user_by_session() cinema_id = current_user['cinema_id'] logging.debug(cinema_id) # self.response.out.write(cinema_id) cinema1 = CinemaHall.get_by_id(cinema_id, parent=testing_key('default')) access = 'Cashier' if (current_user['manager']): access = 'Manager' if (current_user['admin']): access = 'Admin' d = timedelta(hours=5, minutes=30) dtime = datetime.combine(datetime.date(datetime.now() + d), datetime.time(datetime.strptime("9", "%H"))) logging.debug(" " + str(dtime) + " 9hrs") dtime = datetime.now() dtime = d + dtime # dtime = datetime(2013, 03, 10, 11, 14, 30, 0) # self.response.out.write(dtime) # self.response.out.write('<br>') time = datetime.time(dtime) # self.response.out.write(time) today = datetime.date(dtime) # self.response.out.write(today) # self.response.out.write('<br>') show = {} show[1] = datetime.combine(today, cinema1.show_time1) show[2] = datetime.combine(today, cinema1.show_time2) show[3] = datetime.combine(today, cinema1.show_time3) show[4] = datetime.combine(today, cinema1.show_time4) mins45 = timedelta(minutes=45) show[1] += mins45 show[2] += mins45 show[3] += mins45 show[4] += mins45 mins30 = timedelta(minutes=30) mins15 = timedelta(minutes=15) # self.response.out.write(show[1]) # self.response.out.write('<br>') # self.response.out.write(show[2]) # self.response.out.write('<br>') # self.response.out.write(show[3]) # self.response.out.write('<br>') # self.response.out.write(show[4]) # self.response.out.write('<br>') if (dtime < show[1]): s = 1 elif (dtime < show[2]): s = 2 elif (dtime < show[3]): s = 3 elif (dtime < show[4]): s = 4 else: self.display_message( 'No more shows for today. Click <a href="/"> here </a> to go back!' ) return time_diff = show[s] - dtime time_diff = time_diff - mins15 time_in_s = time_diff.total_seconds() time_in_millis = time_in_s * 1000 show_text = "Std. Sale" if (time_in_millis < 0): time_diff = show[s] - dtime time_in_s = time_diff.total_seconds() time_in_millis = time_in_s * 1000 show_text = "Late Sale" logging.debug("Show " + str(s) + " " + str(show[s])) limit = [0, 0, 0, 0, 0, 0] limit[0] = show[s].year limit[1] = show[s].month limit[2] = show[s].day limit[3] = show[s].hour limit[4] = show[s].minute limit[5] = show[s].second logging.debug("**************" + str(show[s].month)) autosubmit = datetime.time(show[s]) showtime = datetime.time(show[s] - mins45) show = str(s) types = [ 'box', 'balcony', 'odc', 'firstclass', ] seats = {} seats1 = {} for type in types: s = Seat.gql('WHERE cinema_id=:1 AND catagory=:2', cinema1.key().id(), type).get() seats[type] = s.number seats1[type] = 0 dtime = datetime.now() d = timedelta(hours=5, minutes=30) dtime = d + dtime today = datetime.date(dtime) #check whether the show record exists: logging.debug(str(show) + " " + str(today) + " " + str(cinema_id)) showrecord = ShowRecord.gql( 'WHERE show=:1 AND date=:2 AND cinema_id=:3', show, today, cinema_id).get() logging.debug(showrecord) if (showrecord): logging.debug(str(showrecord.key().id())) types = [ 'box_full', 'balcony_full', 'balcony_half', 'balcony_service', 'balcony_complimentary', 'odc_full', 'odc_half', 'odc_service', 'odc_complimentary', 'firstclass_full', 'firstclass_half', 'firstclass_service', 'firstclass_complimentary', 'box_full_late', 'balcony_full_late', 'balcony_half_late', 'balcony_service_late', 'balcony_complimentary_late', 'odc_full_late', 'odc_half_late', 'odc_service_late', 'odc_complimentary_late', 'firstclass_full_late', 'firstclass_half_late', 'firstclass_service_late', 'firstclass_complimentary_late', ] notickets = 0 for type in types: ticketsale = TicketSale.gql( 'WHERE show_record_id=:1 AND ticket_type=:2', showrecord.key().id(), type).get() if (ticketsale): seats1[type.split('_')[0]] += ticketsale.sales logging.debug( type.split('_')[0] + str(seats[type.split('_')[0]])) # self.response.out.write(show) # self.response.out.write('<br>') # place = code_no = "B" # run = cinema_id film = "Film" reel = "Reel" # day = 4 # date = datetime.date.today() cinema = cinema1.name place = cinema1.place # code_no = cinema1.code_no # grade = cinema1.grade # time_in_millis = 10000 template_values = { 'show_text': show_text, 'seats': seats, 'seats1': seats1, 'limit': limit, 'cinema_id': cinema_id, 'film': film, 'reel': reel, 'cinema': cinema, 'place': place, 'show': show, 'autosubmit': autosubmit, 'time_in_millis': time_in_millis, 'access': access, 'showtime': showtime, } self.render_template(cinema1.seatplan, template_values)
def date_from_today(n): date_today = date.today() return str( datetime.combine(date_today, time.min) - timedelta(days=n, hours=2))
def test_calender_event(self): # Now I will set recurrence for this event to occur monday and friday of week data = { 'fr': 1, 'mo': 1, 'interval': 1, 'rrule_type': 'weekly', 'end_type': 'end_date', 'final_date': '2011-05-31 00:00:00', 'recurrency': True } self.event_tech_presentation.write(data) # In order to check that recurrent events are views successfully in calendar view, I will open calendar view of events| self.CalendarEvent.fields_view_get(False, 'calendar') # In order to check that recurrent events are views successfully in calendar view, I will search for one of the recurrent event and count the number of events rec_events = self.CalendarEvent.with_context({ 'virtual_id': True }).search([('start', '>=', '2011-04-30 16:00:00'), ('start', '<=', '2011-05-31 00:00:00')]) self.assertEqual(len(rec_events), 9, 'Wrong number of events found') # Now I move a virtual event, to see that a real event is well created and depending from the native recurrence before = self.CalendarEvent.with_context({ 'virtual_id': False }).search([('start', '>=', '2011-04-30 16:00:00'), ('start', '<=', '2011-05-31 00:00:00')]) # We start by detach the event newevent = rec_events[1].detach_recurring_event() newevent.with_context({ 'virtual_id': True }).write({ 'name': 'New Name', 'recurrency': True }) after = self.CalendarEvent.with_context({ 'virtual_id': False }).search([('start', '>=', '2011-04-30 16:00:00'), ('start', '<=', '2011-05-31 00:00:00')]) self.assertEqual( len(after), len(before) + 1, 'Wrong number of events found, after to have moved a virtual event' ) new_event = after - before self.assertEqual(new_event[0].recurrent_id, before.id, 'Recurrent_id not correctly passed to the new event') # Now I will test All day event allday_event = self.CalendarEvent.create({ 'allday': 1, 'privacy': 'confidential', 'start': '2011-04-30 00:00:00', 'stop': '2011-04-30 00:00:00', 'description': 'All day technical test', 'location': 'School', 'name': 'All day test event' }) # In order to check reminder I will first create reminder res_alarm_day_before_event_starts = self.env['calendar.alarm'].create({ 'name': '1 Day before event starts', 'duration': 1, 'interval': 'days', 'alarm_type': 'notification' }) # Now I will assign this reminder to all day event| allday_event.write( {'alarm_ids': [(6, 0, [res_alarm_day_before_event_starts.id])]}) # I create a recuring rule for my event calendar_event_sprint_review = self.CalendarEvent.create({ 'name': 'Begin of month meeting', 'start': datetime.combine(fields.Date.today(), time(12, 0)), 'stop': datetime.combine(fields.Date.today(), time(18, 0)), 'recurrency': True, 'rrule': 'FREQ=MONTHLY;INTERVAL=1;COUNT=12;BYDAY=1MO' }) # I check that the attributes are set correctly self.assertEqual(calendar_event_sprint_review.rrule_type, 'monthly', 'rrule_type should be mothly') self.assertEqual(calendar_event_sprint_review.count, 12, 'rrule_type should be mothly') self.assertEqual(calendar_event_sprint_review.month_by, 'day', 'rrule_type should be mothly') self.assertEqual(calendar_event_sprint_review.byday, '1', 'rrule_type should be mothly') self.assertEqual(calendar_event_sprint_review.week_list, 'MO', 'rrule_type should be mothly')
def from_db_value(self, value, expression, connection): if value: return datetime.combine(value.date(), value.time())
def main(): # Parse parameters num_runs = 1 episodes = 10000 parser = argparse.ArgumentParser( description="Reinforcement Learning for the Gym") parser.add_argument("--render", action="store_true", default=False, help="Enable a graphical rendering of the environment") parser.add_argument("--monitor", action="store_true", default=False, help="Enable Gym monitoring for this run") parser.add_argument("--env", required=True, type=str, help="Gym environment to use") parser.add_argument("--avg", type=int, default=1, help="Episodes run between gradient updates") parser.add_argument("--episodes", type=int, default=1000, help="Number of episodes to run") parser.add_argument("--name", type=str, default='', help="Experiment name") parser.add_argument( "--ret", type=str, choices=['forward', 'both'], default='both', help= 'Type of return used for training, only forward-looking or also using accumulated rewards' ) parser.add_argument("--utility", type=str, help="Utility function, a function of r1 to rN") parser.add_argument( "--extra-state", type=str, choices=['none', 'timestep', 'accrued', 'both'], default='none', help= 'Additional information given to the agent, like the accrued reward') parser.add_argument("--hidden", default=50, type=int, help="Hidden neurons of the policy network") parser.add_argument("--lr", default=1e-3, type=float, help="Learning rate of the neural network") # Next and Sub from arguments args = parser.parse_args() import time # Instantiate learner #learner = Learner(args) df = pd.DataFrame() # Learn f = open('DeepSeaTreasure-Experiment-Output', 'w') start_time = datetime.time(datetime.now()) if args.monitor: learner._env.monitor.start('/tmp/monitor', force=True) for run in range(num_runs): runData = [] learner = Learner(args) try: #old_dt = datetime.datetime.now() avg = np.zeros(shape=(learner._num_rewards, )) for i in range(episodes): rewards = learner.run() if i == 0: avg = rewards else: #avg = 0.99 * avg + 0.01 * rewards avg = avg + rewards #print("Percentage Completed....", i%100, "% ", "Run : ", num_runs, " Episode : ", i, file = f) scalarized_avg = learner.scalarize_reward(avg) if i < 0: learner.epsilon = 1.0 else: learner.epsilon = learner.epsilon * 0.99 if learner.epsilon < 0.001: learner.epsilon = 0.001 if i % 100 == 0 and i >= 0: r = (i / episodes) * 100 time = datetime.time(datetime.now()) time_elapsed = datetime.combine( date.today(), time) - datetime.combine( date.today(), start_time) print("Percentage Completed...", r, "% ", "Run : ", run, "Time Elapsed : ", time_elapsed, "Average Reward : ", scalarized_avg, file=f) f.flush() print("Cumulative reward:", rewards, file=f) #print("Cumulative reward:", rewards, "; average rewards:", avg, scalarized_avg, file=f) #print(args.name, "Cumulative reward:", rewards, "; average rewards:", avg, scalarized_avg) runData.append(scalarized_avg) #print("Run Data:", runData, file = f) f.flush() #data = pd.DataFrame({"Run " + str(run) : runData}) #df = df.append(data) df['Run ' + str(run)] = runData #print("DataFrame:", df, file = f) #f.flush() except KeyboardInterrupt: pass if args.monitor: learner._env.monitor.close() t = datetime.now() #timestamp = time.strftime('%b-%d-%Y_%H-%M-%S', t) df.to_csv(r'Experiments/Exp_MODistRL_TreeSearch_' + str(t) + '.csv')
# print( delta) # t = datetime.now() # print(t) # t1 = datetime.time(3, 2, 1) # td = t1 - datetime.timedelta(hours=2, minutes=10) # t2 = datetime.time(3, 2, 1) # t = datetime.datetime.now() - datetime.timedelta(hours=2, minutes=10) # print( t) # import datetime # import time # t1 = datetime.time(00, 10, ) # print ('\tt1:', t1 ) # t2 = datetime.time(23, 55, ) # print ('\tt2:', t2 ) # print ('\tt1 > t2:', t1 > t2 ) # Parsing the time hora = '00:10:10' # 12:10 t2 = datetime.time(*[int(i) for i in hora.split(":")]) hora = '00:20:10' # 12:10 t1 = datetime.time(*[int(i) for i in hora.split(":")]) datetime.combine(date.today(), t1) - datetime.combine(date.today(), t2)
from multiprocessing.sharedctypes import Value, Array import pandas as pd #import scipy.sparse as sp #import numpy as np #from sklearn.metrics.pairwise import cosine_similarity #from __builtin__ import range from string import join from logging import exception from pymongo import Connection import csv import pdb todayDate = date.today() requiredDate = todayDate + relativedelta(days=-25) requiredDate1 = todayDate + relativedelta(days=-12) day2 = datetime.combine(requiredDate, time(0, 0)) day21 = datetime.combine(requiredDate1, time(0, 0)) def getMongoConnection(MONGO_HOST, MONGO_PORT, DB, isSlave=False, isAuth=False, username='******', password='******'): if isAuth: connection = Connection(MONGO_HOST, MONGO_PORT, slave_okay=isSlave, username=username,
def midnight(): return datetime.combine(datetime.now(), time(0, 0, 0, tzinfo=self.localtz))
def UserTimes(): if request.method == "POST": db.execute("DELETE FROM UserTimes WHERE UserID=:userid", userid=session["user_id"]) #deletes previous usertimes inputs in the database for that user arr = request.get_json() available = arr["jsonArr"][0] preferred = arr["jsonArr"][1] #using json to request the inputs sent by the ajax call in the UserTimes.html page for t in available: for day in weekdays: if day in t: t = t[len(day):] StartTime = t[:5] EndTime = t[-5:] db.execute( "INSERT INTO UserTimes (TimesID, UserID, DayOfTheWeek, StartTime, EndTime, AorP) VALUES (NULL, :userid, :day, :st, :et, 'A');", userid=session["user_id"], day=day, st=StartTime, et=EndTime) #looping through the inputs recieved for available time then formatting the string and splitting it up into start time and end time so it can be inputted into the database for t in preferred: for day in weekdays: if day in t: t = t[len(day):] StartTime = t[:5] EndTime = t[-5:] db.execute( "INSERT INTO UserTimes (TimesID, UserID, DayOfTheWeek, StartTime, EndTime, AorP) VALUES (NULL, :userid, :day, :st, :et, 'P');", userid=session["user_id"], day=day, st=StartTime, et=EndTime) #same is done for the preferred times array SignUpCompleted = db.execute( "SELECT SignUpCompleted FROM Users WHERE UserID = :userid", userid=session["user_id"]) if (SignUpCompleted[0]['SignUpCompleted'] == 1): return redirect("/timetableCreate") else: return redirect("/subject") #if the sign up process has been completed the user is redirected to the timetable and if not they are redirected to the subjects page else: duration = db.execute( "SELECT DurationOfBlocks FROM UserInfo WHERE UserID=:userid;", userid=session["user_id"]) duration = duration[0]["DurationOfBlocks"] dayTimes = { "Sunday": [], "Monday": [], "Tuesday": [], "Wednesday": [], "Thursday": [], "Friday": [], "Saturday": [] } #creating a dictionary of all the days of the week to create all the times that need to be displayed on the page i = 0 sleepSchedule = db.execute( "SELECT * FROM DayTimes WHERE UserID=:userid;", userid=session["user_id"]) #getting day time inputs from the database for item in sleepSchedule: if item["Day"] == weekdays[i]: nextdaytimes = [ "00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00", "11:00", "12:00" ] #if these times are entered as sleep times the application will consider them times in the next day as they are in the morning wakeup = item["WakeUp"] sleep = item["Sleep"] if sleep in nextdaytimes: sleep = datetime.combine( date.today(), time(int(sleep[:2]), int(sleep[3:]))) sleep += timedelta(days=1) #adds a day to time if it is in nextdaytimes else: sleep = datetime.combine( date.today(), time(int(sleep[:2]), int(sleep[3:]))) dt = datetime.combine(date.today(), time(int(wakeup[:2]), int(wakeup[3:]))) dayTimes[weekdays[i]].append(dt.strftime("%H:%M")) #formating the waking time and adding it to its corresponding weekday array in the day times array (2D array) while dt < sleep: dt += timedelta(minutes=duration) dayTimes[weekdays[i]].append(dt.strftime("%H:%M")) #adding the duration selected in user preferences to the waking time and appending that result to the array #this creates a list of times which are then displayed i += 1 for day in dayTimes: times = dayTimes[day] for i in range(len(times)): if i == 0: continue else: times[i - 1] = times[i - 1] + "-" + times[i] dayTimes[day] = times[:-1] #iterates through times and joins wake time and sleep times into one variable while putting a ':' in the middle #this is so they look like this - '08:00-09:00' SignUpCompleted = db.execute( "SELECT SignUpCompleted FROM Users WHERE UserID = :userid", userid=session["user_id"]) if (SignUpCompleted[0]['SignUpCompleted'] == 1): redirectPage = "http://localhost:5000/timetableCreate" else: redirectPage = "http://localhost:5000/subject" return render_template("UserTimes.html", dayTimes=dayTimes, redirectPage=redirectPage)
import pandas as pd import scipy.sparse as sp import numpy as np from sklearn.metrics.pairwise import cosine_similarity from __builtin__ import range from string import join from logging import exception todayDate = date.today() interval1 = 365 previousDate = todayDate + relativedelta(days=-1) oneYearWindow = todayDate + relativedelta(days=-interval1) previousYearDate = oneYearWindow + relativedelta(days=-1) day1 = datetime.combine(todayDate, time(0, 0)) day2 = datetime.combine(oneYearWindow, time(0, 0)) projectHome = '/data/Projects/SimilarJobs' # #Mongo Connection def getMongoConnection(MONGO_HOST, MONGO_PORT, DB, isAuth=False, username='******', password='******'): if isAuth: connection = MongoClient(MONGO_HOST, MONGO_PORT, read_preference=ReadPreference.SECONDARY) mongo_conn = connection[DB] mongo_conn.authenticate(username, password) else: connection = MongoClient(MONGO_HOST, MONGO_PORT, read_preference=ReadPreference.SECONDARY) mongo_conn = connection[DB] return mongo_conn
async def fish(self, ctx): """Go Fishing!""" enabled = await self.config.guild(ctx.guild).enabled() if not enabled: return await ctx.send("Uh oh, the lake is closed. Come back later!" ) casting_price = 5 balance = int(await bank.get_balance(ctx.author)) credits_name = await bank.get_currency_name(ctx.guild) if casting_price > balance: return await ctx.send( f"It cost's {casting_price} {credits_name} to buy bait. You don't have enough!" ) author = ctx.message.author userdata = await self.config.user(ctx.author).all() last_time = datetime.strptime(str(userdata["last_fish"]), "%Y-%m-%d %H:%M:%S.%f") now = datetime.now(timezone.utc) now = now.replace(tzinfo=None) seconds = int((now - last_time).total_seconds()) cd = await self.config.guild(ctx.guild).cooldown() secs = cd - seconds if int((now - last_time).total_seconds()) < await self.config.guild( ctx.guild).cooldown(): return await ctx.send( f"<:Fishing:782681118674780200> **| {author.name} you can fish again in {secs} seconds.**", delete_after=secs) await self.config.user(ctx.author).last_fish.set(str(now)) await bank.withdraw_credits(ctx.author, casting_price) #Daily cog input. memberdata = await self.bot.get_cog("Daily").config.member(ctx.author ).all() fishing = memberdata["fishing"] fishing_count = memberdata["fishing_count"] fishing_quest = memberdata["fishing_quest"] fishing_credits = memberdata["fishing_credits"] #Update midnight values today = date.today() midnight_today = datetime.combine(today, datetime.min.time()) midnight_check = datetime.strptime(str(midnight_today), "%Y-%m-%d %H:%M:%S") await self.bot.get_cog("Daily").config.midnight_today.set( str(midnight_check)) #Pull when their last quest was built quests_built = datetime.strptime(str(memberdata["quests_built"]), "%Y-%m-%d %H:%M:%S") chance = uniform(0, 99) rarechance = 0.15 uncommonchance = 10.15 commonchance = 74 if chance <= rarechance: rarefish = await self.config.rarefish() # mn = len(rarefish) # r = randint(0, mn - 1) # fish = rarefish[r] fish = (random.choice(rarefish)) item = RARES[fish] await ctx.send(( "<:Fishing:782681118674780200> **| {author.name}** caught a **{item}**, it's **rare!!! |** {fish}\n" "Type `!rarefish` to see your trophy room").format( author=author, item=item, fish=fish, )) #Fishing module quest check/completion await self.bot.get_cog("Daily").config.member( ctx.author).fishing_count.set(fishing_count + 1) fishing_count = fishing_count + 1 if fishing_count == fishing_quest: if quests_built < midnight_check: pass elif fishing == False: credits = int(fishing_credits) await bank.deposit_credits(ctx.author, credits) await ctx.send( f"<:Coins:783453482262331393> **| Fishing quest complete!**\n<:Coins:783453482262331393> **| Reward:** {fishing_credits} {credits_name}" ) await self.bot.get_cog("Daily").config.member(ctx.author ).fishing.set(1) try: item = RARES[fish] fish_info = await self.bot.get_cog("Shop").config.member( ctx.author).inventory.get_raw(item) author_quantity = int(fish_info.get("quantity")) author_quantity += 1 await self.bot.get_cog("Shop").config.member( ctx.author).inventory.set_raw(item, "quantity", value=author_quantity) if item == "Turtle": await self.config.user(ctx.author ).turtle.set(userdata["turtle"] + 1) elif item == "Blow whale": await self.config.user( ctx.author).blow_whale.set(userdata["blow_whale"] + 1) elif item == "Whale": await self.config.user(ctx.author ).whale.set(userdata["whale"] + 1) elif item == "Crocodile": await self.config.user( ctx.author).crocodile.set(userdata["crocodile"] + 1) elif item == "Penguin": await self.config.user( ctx.author).penguin.set(userdata["penguin"] + 1) elif item == "Octopus": await self.config.user( ctx.author).octopus.set(userdata["octopus"] + 1) elif item == "Shark": await self.config.user(ctx.author ).shark.set(userdata["shark"] + 1) elif item == "Squid": await self.config.user(ctx.author ).squid.set(userdata["squid"] + 1) elif item == "Dolphin": await self.config.user( ctx.author).dolphin.set(userdata["dolphin"] + 1) except KeyError: item = RARES[fish] price = 2000 author_quantity = 1 description = "Oooo shiny!" await self.bot.get_cog("Shop").config.member( ctx.author).inventory.set_raw( item, value={ "price": price, "quantity": author_quantity, "is_item": False, "is_role": False, "is_game": False, "is_xmas": False, "is_fish": True, "redeemable": False, "redeemed": False, "description": description, "giftable": False, "gifted": False, }, ) if item == "Turtle": await self.config.user(ctx.author ).turtle.set(userdata["turtle"] + 1) elif item == "Blow whale": await self.config.user( ctx.author).blow_whale.set(userdata["blow_whale"] + 1) elif item == "Whale": await self.config.user(ctx.author ).whale.set(userdata["whale"] + 1) elif item == "Crocodile": await self.config.user( ctx.author).crocodile.set(userdata["crocodile"] + 1) elif item == "Penguin": await self.config.user( ctx.author).penguin.set(userdata["penguin"] + 1) elif item == "Octopus": await self.config.user( ctx.author).octopus.set(userdata["octopus"] + 1) elif item == "Shark": await self.config.user(ctx.author ).shark.set(userdata["shark"] + 1) elif item == "Squid": await self.config.user(ctx.author ).squid.set(userdata["squid"] + 1) elif item == "Dolphin": await self.config.user( ctx.author).dolphin.set(userdata["dolphin"] + 1) elif rarechance < chance <= uncommonchance: uncommon = await self.config.uncommon() # mn = len(uncommon) # u = randint(0, mn - 1) # fish = uncommon[u] fish = (random.choice(uncommon)) await ctx.send( f"<:Fishing:782681118674780200> **| {author.name}** caught an **uncommon fish! |** {fish}" ) #Fishing module quest check/completion await self.bot.get_cog("Daily").config.member( ctx.author).fishing_count.set(fishing_count + 1) fishing_count = fishing_count + 1 if fishing_count == fishing_quest: if quests_built < midnight_check: pass elif fishing == False: credits = int(fishing_credits) await bank.deposit_credits(ctx.author, credits) await ctx.send( f"<:Coins:783453482262331393> **| Fishing quest complete!**\n<:Coins:783453482262331393> **| Reward:** {fishing_credits} {credits_name}" ) await self.bot.get_cog("Daily").config.member(ctx.author ).fishing.set(1) try: item = NAMES[fish] fish_info = await self.bot.get_cog("Shop").config.member( ctx.author).inventory.get_raw(item) author_quantity = int(fish_info.get("quantity")) author_quantity += 1 await self.bot.get_cog("Shop").config.member( ctx.author).inventory.set_raw(item, "quantity", value=author_quantity) except KeyError: item = NAMES[fish] price = 50 author_quantity = 1 description = "Don't see these too often!" await self.bot.get_cog("Shop").config.member( ctx.author).inventory.set_raw( item, value={ "price": price, "quantity": author_quantity, "is_item": False, "is_role": False, "is_game": False, "is_xmas": False, "is_fish": True, "redeemable": False, "redeemed": False, "description": description, "giftable": False, "gifted": False, }, ) elif uncommonchance < chance <= commonchance: common = await self.config.common() # mn = len(common) # c = randint(0, mn - 1) # fish = common[c] fish = (random.choice(common)) await ctx.send( f"<:Fishing:782681118674780200> **| {author.name}** caught a **common fish |** {fish}" ) #Fishing module quest check/completion await self.bot.get_cog("Daily").config.member( ctx.author).fishing_count.set(fishing_count + 1) fishing_count = fishing_count + 1 if fishing_count == fishing_quest: if quests_built < midnight_check: pass elif fishing == False: credits = int(fishing_credits) await bank.deposit_credits(ctx.author, credits) await ctx.send( f"<:Coins:783453482262331393> **| Fishing quest complete!**\n<:Coins:783453482262331393> **| Reward:** {fishing_credits} {credits_name}" ) await self.bot.get_cog("Daily").config.member(ctx.author ).fishing.set(1) try: item = NAMES[fish] fish_info = await self.bot.get_cog("Shop").config.member( ctx.author).inventory.get_raw(item) author_quantity = int(fish_info.get("quantity")) author_quantity += 1 await self.bot.get_cog("Shop").config.member( ctx.author).inventory.set_raw(item, "quantity", value=author_quantity) except KeyError: item = NAMES[fish] price = 10 author_quantity = 1 description = "Another one of these? Ok!" await self.bot.get_cog("Shop").config.member( ctx.author).inventory.set_raw( item, value={ "price": price, "quantity": author_quantity, "is_item": False, "is_role": False, "is_game": False, "is_xmas": False, "is_fish": True, "redeemable": False, "redeemed": False, "description": description, "giftable": False, "gifted": False, }, ) elif chance > commonchance: trash = await self.config.trash() # mn = len(trash) # t = randint(0, mn - 1) # fish = trash[t] fish = (random.choice(trash)) await ctx.send( f"<:Fishing:782681118674780200> **| {author.name}** caught a piece of **trash |** {fish}" ) #Fishing module quest check/completion await self.bot.get_cog("Daily").config.member( ctx.author).fishing_count.set(fishing_count + 1) fishing_count = fishing_count + 1 if fishing_count == fishing_quest: if quests_built < midnight_check: pass elif fishing == False: credits = int(fishing_credits) await bank.deposit_credits(ctx.author, credits) await ctx.send( f"<:Coins:783453482262331393> **| Fishing quest complete!**\n<:Coins:783453482262331393> **| Reward:** {fishing_credits} {credits_name}" ) await self.bot.get_cog("Daily").config.member(ctx.author ).fishing.set(1) try: item = NAMES[fish] fish_info = await self.bot.get_cog("Shop").config.member( ctx.author).inventory.get_raw(item) author_quantity = int(fish_info.get("quantity")) author_quantity += 1 await self.bot.get_cog("Shop").config.member( ctx.author).inventory.set_raw(item, "quantity", value=author_quantity) except KeyError: item = NAMES[fish] price = 5 author_quantity = 1 description = "Ugh, trash" await self.bot.get_cog("Shop").config.member( ctx.author).inventory.set_raw( item, value={ "price": price, "quantity": author_quantity, "is_item": False, "is_role": False, "is_game": False, "is_xmas": False, "is_fish": True, "redeemable": False, "redeemed": False, "description": description, "giftable": False, "gifted": False, }, )
print("Current time is: {}:{}:{}".format(today.hour, today.minute, today.second)) """ One can also combine a date object and a time object to form a datetime object. """ from datetime import date, time, datetime import time as tim d = date(month=3, year=2020, day=6) #Creates a date object t = time(minute=45, hour=2, second=18) #Creates a time object #Sleep/Freeze the execution of your program/script using sleep() method from #the time module tim.sleep(4) dt = datetime.combine(d, t) print(dt) """ Sorting Date Object using list Object. This involves adding the date object inside the list and call the sort method of the list. The performance of a program/script (i.e. the execution time) can be calculated using the perf_counter() method from the 'time' module. To accomplish this put it as the beginning and end of your code, the subtract and the difference is your execution time. e.g. startTime = time.perf_counter() ====your code goes here====
def to_python(self, value): if value: dt = models.DateTimeField().to_python(value) return datetime.combine(dt.date(), dt.time())
import csv todayDate=date.today() file_date = todayDate+relativedelta(days=-1) file_date = file_date.strftime("%d-%b-%Y") todayDate = todayDate.strftime("%d-%b-%Y") todayDate = datetime.strptime(todayDate,"%d-%b-%Y") previousDate=todayDate+relativedelta(days=-1) previousDate = previousDate.strftime("%d-%b-%Y") previousDate = datetime.strptime(previousDate,"%d-%b-%Y") Month = previousDate.strftime("%b-%Y") Year = previousDate.strftime("%Y") day1 = datetime.combine(previousDate, time(0, 0)) day2 = datetime.combine(todayDate, time(0, 0)) def getMongoConnection(MONGO_HOST,MONGO_PORT,DB, isSlave=False, isAuth=False, username = '******', password = '******'): if isAuth: connection = Connection(MONGO_HOST,MONGO_PORT, slave_okay = isSlave, username = username, password = password) else: connection = Connection(MONGO_HOST,MONGO_PORT, slave_okay = isSlave) mongo_conn = connection[DB] mongo_conn.authenticate(username, password) return mongo_conn mongo_conn = getMongoConnection('172.22.65.157',27018, 'sumoplus',True, True) collection = getattr(mongo_conn, 'CandidateStatic') collection_1 = getattr(mongo_conn, 'LookupExperience')
def get_last_sunday(today): curr = today while (curr.weekday() != 6): curr = curr - timedelta(days=1) curr = datetime.combine(curr, time()) return curr
def show_my_cham(request, num_chamG, idG): if num_chamG == "None": try: obj= chamado_hse.objects.all().latest('data_abertura') except chamado_hse.DoesNotExist: raise Http404("Nenhum Chamado Existente para sua Empresa.") else: num_cham = decodif(num_chamG) obj= chamado_hse.objects.get(id = num_cham) id = decodif(idG) arr = [] dict = {} cont = 0 for x in obj.tipo_servico: if x == '1': arr.insert(cont,'Trabalho em alta tensão e eletricidade') dict = {'CURSO DE ELETRICISTA':'Trabalho em alta tensão e eletricidade','ASO ALTA TENSÃO':'Trabalho em alta tensão e eletricidade','CURSO NR 10 OU RECICLAGEM':'Trabalho em alta tensão e eletricidade',} if x == '2': arr.insert(cont,'Trabalhos em altura') cont = cont + 1 dict.update({'CERTIFICADO TREINAMENTO NR35':'Trabalhos em altura','ASO TRABALHOS EM ALTURA':'Trabalhos em altura','FICHA DE EPI':'Trabalhos em altura',}) if x == '3': arr.insert(cont,'Espaços confinados') cont = cont + 1 dict.update({'CERTIFICADO TREINAMENTO DE VIGIA':'Espaços confinados','ASO ESPAÇO CONFINADO':'Espaços confinados','FICHA DE EPI':'Espaços confinados',}) if x == '4': arr.insert(cont,'Operação de empilhadeira') cont = cont + 1 dict.update({'ASO DA ADMISSÃO':'Operação de empilhadeira','CERTIFICADO OPERADOR EMPILHADEIRA':'Operação de empilhadeira',}) if x == '5': arr.insert(cont,'Trabalhos com plataformas elevatórias') cont = cont + 1 dict.update({'CURSO OPERADOR PLATAFORMA ELEVATÓRIA':'Trabalhos com plataformas elevatórias','ASO DA ADMISSÃO':'Trabalhos com plataformas elevatórias',}) if x == '6': arr.insert(cont,'Operação de guindaste ou munck') cont = cont + 1 dict.update({'CURSO DE GUINDASTE E/OU MUNCK':'Operação de guindaste ou munck','ASO DA ADMISSÃO':'Operação de guindaste ou munck','RINGGING PARA GUINDASTES':'Operação de guindaste ou munck',}) if x == '7': arr.insert(cont,'Trabalhador autônomo - Firma individual') cont = cont + 1 dict.update({'REGISTRO DA PREFEITURA':'Trabalhador autônomo - Firma individual','ASO':'Trabalhador autônomo - Firma individual','NÚMERO DE MATRÍCULA INSS':'Trabalhador autônomo - Firma individual',}) if x == '8': arr.insert(cont,'Assistência Técnica - mautenção') cont = cont + 1 dict.update({'CRACHÁ OU CARTEIRA PROFISSIONAL':'Assistência Técnica - mautenção','ASO':'Assistência Técnica - mautenção',}) if x == '9': arr.insert(cont,'Soldador') cont = cont + 1 dict.update({'PPRA DE SOLDA':'Soldador','COMPROVANTE DE CURSO OU EXPERIÊNCIA':'Soldador','FICHA DE EPI SOLDA':'Soldador',}) emp = empresa_terc.objects.all() N_CHM = '%0*d' % (5, obj.id) mycham= chamado_hse.objects.filter(empresa_id = id) data = datetime.strptime(obj.tempo_estimado, '%m/%d/%Y') dt = datetime.combine(data, time(00, 00)) - timedelta(days=4) minus4 = dt.date() - timedelta(days=4) minus6 = dt.date() - timedelta(days=6) d1 = datetime.strptime(timezone.localtime().strftime('%Y-%m-%d'), "%Y-%m-%d").date() d2 = datetime.strptime(minus6.strftime('%Y-%m-%d'), "%Y-%m-%d").date() qt = dias(data.date(), obj.data_abertura.date()) alist = list(sorted(qt.keys())) rest = (d2 - d1).days if rest > 0: rest = "RESTAM " + str(abs((d1 - d2).days)) elif rest == 0: rest = "VENCIMENTO HOJE !" else: rest = "ATRASADO ! " + str(abs((d1 - d2).days)) obj.data = minus6 obj.save() fun = funcionario.objects.filter(Q(empresa_id = id) & ~Q(rg="BLOQUEADO")) dc = chamado_hse.objects.filter(empresa_id = id) colab = aux_table.objects.filter(num_cham = obj.id) log = logs.objects.filter(num_cham = obj.id) msgs = msg.objects.filter(num_cham = obj.id) func = funcionario.objects.filter(empresa_id=id) #Us = User.objects.get(username=obj.gestor_solicitante)'Em_g':Us.email, respo = cad_resp.objects.filter(empresa_resp=id) return render(request, 'chamados.html', {'qt':alist, 'respo':respo, 'dw':data.date(), 'func':func, 'msgs':msgs,'log':log,'colab':colab,'id':id,'fun':fun,'obj':obj,'N_CHM':N_CHM,'emp':emp,'mycham':mycham,'minus4':minus4,'minus6':minus6,'rest':rest,'arr':arr,'dict':dict})
def post(self): dtime = datetime.now() d = timedelta(hours=5, minutes=30) dtime = d + dtime today = datetime.date(dtime) show = self.request.get('show') s = int(show) cinema_id = int(self.request.get('cinema_id')) cinema1 = CinemaHall.get_by_id(cinema_id, parent=testing_key('default')) cinema_nfc = cinema1.nfc cinema_theatre = cinema1.theatre #check whether the show record exists: logging.debug(str(show) + " " + str(today) + " " + str(cinema_id)) showrecord = ShowRecord.gql( 'WHERE show=:1 AND date=:2 AND cinema_id=:3', show, today, cinema_id).get() logging.debug(showrecord) qResult = ShowHistory.gql('WHERE cinema_id=:1 AND start_date<=:2', cinema_id, today).get() reel = Reel.get_by_id(qResult.reel_id, parent=testing_key('default')) film = Film.get_by_id(reel.film_id, parent=testing_key('default')) if (qResult.threeD): is3D = True else: is3D = False show = {} show[1] = datetime.combine(today, cinema1.show_time1) show[2] = datetime.combine(today, cinema1.show_time2) show[3] = datetime.combine(today, cinema1.show_time3) show[4] = datetime.combine(today, cinema1.show_time4) showtime = datetime.time(show[s]) mins30 = timedelta(minutes=30) show[1] += mins30 show[2] += mins30 show[3] += mins30 show[4] += mins30 mins1 = timedelta(minutes=1) latesale = False if (dtime > show[s] + mins1): latesale = True show = s if not (showrecord): showrecord = ShowRecord(parent=testing_key('default')) showrecord.cinema_id = int(self.request.get('cinema_id')) showrecord.show = self.request.get('show') current_user = self.auth.get_user_by_session() showrecord.user_nic = current_user[ 'first_name'] + " " + current_user['last_name'] showrecord.date = today showrecord.weather = self.request.get('weather') showrecord.remarks = self.request.get('remarks') # self.response.out.write('Success') showrecord.put() show_id = showrecord.key().id() ticket_text = [] ticket_details = {} prices = [] types = ['odc_full', 'odc_half', 'odc_service', 'odc_complimentary'] notickets = 0 new_ticketsale = False total_price = 0 inc = 0 ticketprint = {} seatNumbers = self.request.get('seatListString').split(',') seatNumbersIndex = 0 for type in types: type_inc = 0 if (latesale): ticketsale = TicketSale.gql( 'WHERE show_record_id=:1 AND ticket_type=:2', show_id, type + '_late').get() # self.redirect('www.google.com') else: ticketsale = TicketSale.gql( 'WHERE show_record_id=:1 AND ticket_type=:2', show_id, type).get() if not (ticketsale): new_ticketsale = True ticketsale = TicketSale(parent=showrecord) ticketsale.show_record_id = show_id ticketsale.ticket_type = type if (latesale): ticketsale.ticket_type = ticketsale.ticket_type + '_late' ticketsale.sales = 0 ticketreserve = TicketReservation(parent=showrecord) #seat_number=db.StringProperty() #ticket_type=db.StringProperty() #show_record_id = db.IntegerProperty() #late_sale=db.B qResult = Tariff.gql( 'WHERE cinema_id=:1 AND ticket_type=:2 AND type=:3', showrecord.cinema_id, type, 'basic').get() qResult2 = Tariff.gql( 'WHERE cinema_id=:1 AND ticket_type=:2 AND type=:3', showrecord.cinema_id, type, 'ent').get() ticketsale.sales += int(self.request.get(type)) if (int(self.request.get(type))): price = qResult.rate price += qResult2.rate price += (cinema_nfc + cinema_theatre) if (is3D): price += 100.0 price2 = price * int((self.request.get(type))) if (type.split('_')[1] == 'complimentary'): price = price2 = 0.0 total_price += price2 ticket_text.append("" + type + " : " + (self.request.get(type)) + " x " + str(price) + " = " + str(price2)) for x in range(0, int((self.request.get(type)))): ticketprint[inc] = TicketPrint() ticketprint[inc].cinema_hall = cinema1.name ticketprint[inc].cinema_place = cinema1.place ticketprint[inc].film_name = film.name ticketprint[inc].show_time = showtime ticketprint[inc].seat_type = str.upper(type.split('_')[0]) ticketprint[inc].ticket_type = str.upper( type.split('_')[1]) ticketprint[inc].ticket_no = (qResult.opening + type_inc) ticketprint[inc].price = "LKR " + str(price) + "0" ticketprint[inc].seat_number = seatNumbers[ seatNumbersIndex] ticketreserve.seat_number = seatNumbers[seatNumbersIndex] ticketreserve.ticket_type = str.upper( type.split('_')[0] + "_" + type.split('_')[1]) ticketreserve.show_record_id = show_id ticketreserve.late_sale = latesale if (type.split('_')[1] == 'complimentary'): ticketprint[inc].price = "FREE" prices.append(price) # ticket_details[notickets] = (self.request.get(type)) # ticket_details[notickets].price = str(price) # ticket_detaisl[notickets].aggregrate = str(price2) notickets += 1 inc += 1 type_inc += 1 seatNumbersIndex += 1 ticketreserve.put() if (qResult): if (new_ticketsale): ticketsale.opening_number = qResult.opening qResult.opening += int(self.request.get(type)) qResult.put() else: ticketsale.opening_number = 0 ticketsale.put() logging.info(ticket_text) ticket_text.append("Total Price : " + str(total_price)) template_values = { "ticketprint": ticketprint, "total_price": total_price, "prices": prices, "ticket_text": ticket_text, "ticket_details": ticket_details, "seat_list": seatNumbers } if (notickets > 0): #if(False): self.render_template('sample-reserve.html', template_values) # self.display_message('Ticket Sale Information<br>'+str(dtime)+'<br>'+ticket_text+'</ol><br>Click <a href="/tickets"> here </a> to go back to sales!') return self.redirect('/tickets')
def predict(webcam): print(webcam["city"]) # vedere se posso prendere solo le città per poi fare query distinte table = pandas.DataFrame( Detection.objects(city=webcam['city'], type=0).as_pymongo()) #prelevo i dati di roma table = table.dropna() print(table.shape) most_freq = lambda x: x.value_counts(dropna=True).index[0] table_a = table table_a = table_a.drop(columns=[ '_id', 'id_webcam', 'city', 'type', 'date', 'location', 'latitude', 'longitude' ]) table_a['time'] = pandas.to_datetime(table_a['time']) table_a.sort_values(by='time', inplace=True) tb = table_a.groupby([pandas.Grouper(key='time', freq='30T')], as_index=False).agg(time=('time', most_freq), meanPeople=('numPeople', 'mean'), temp=('temperature', 'mean'), weather=('weather_description', most_freq), day_of_week=('day_of_week', most_freq)) tb = tb.dropna() tb.plot('time', 'meanPeople') forecast = pandas.DataFrame( weather_forecast.objects(latitude=webcam['latitude']).as_pymongo() ) #prelevo i dati di Djakovo forecast = forecast.drop(columns=['_id', 'latitude', 'longitude']) forecast['datetime'] = pandas.to_datetime(forecast['datetime']) forecast = forecast.groupby('datetime').first().reset_index() forecast.sort_values(by='datetime', inplace=True) today = datetime.today() tomorrow = today + timedelta(days=1) midnight0 = datetime.combine(today, datetime.min.time()) midnight1 = datetime.combine(tomorrow, datetime.min.time()) forecast = forecast.loc[(forecast['datetime'] >= midnight0)] forecast = forecast.loc[(forecast['datetime'] < midnight1)].reset_index() # print(forecast.to_markdown()) weekday = np.full((24, 1), today.weekday()) fc = pandas.DataFrame() fc.insert(0, 'time', np.arange(0, 24)) fc.insert(1, 'temp', forecast['temperature'].iloc[0:24]) fc.insert(2, 'weather', forecast['weather_description'].iloc[0:24]) fc.insert(3, 'day_of_week', weekday[0:24]) print(fc) forecast_dummies = fc['weather'].unique() print(forecast_dummies.shape) detection_dummies = tb['weather'].unique() print(detection_dummies.shape) # print(np.concatenate((forecast_dummies, detection_dummies), axis=0)) le = sklearn.preprocessing.LabelEncoder() le.classes_ = np.unique( np.concatenate((forecast_dummies, detection_dummies), axis=0)) fc['weather'] = le.transform(fc['weather']) tb['weather_dummy'] = le.transform(tb['weather']) print(fc) tb['time'] = tb['time'].dt.hour tb = tb.dropna() tb = tb.reset_index() #divide the dataframe 70-30 for train and test x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split( tb[['time', 'temp', 'day_of_week', 'weather_dummy']], tb['meanPeople'], test_size=0.33, shuffle=True, random_state=42) #Modello tipo Regressione Lineare standard modelLReg = sklearn.linear_model.LinearRegression() #provo a dargli in pasto tutto #prima di questo ora bisogna dividere tutto il dataset in 70-30 modelLReg.fit(x_train, y_train) # The coefficients print('Coefficients: \n', modelLReg.coef_) # The mean square error print("Residual sum of squares: %.2f" % np.mean( (modelLReg.predict(x_test) - y_test)**2)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % modelLReg.score(x_test, y_test)) #Modello tipo Forest modelForest = RandomForestRegressor(n_estimators=1000) modelForest.fit(x_train, y_train) pickle.dump(modelForest, open("modelForest_" + webcam['location'] + ".pkl", "wb")) print('Forest score : %.2f' % modelForest.score(x_test, y_test)) forest_prediction = modelForest.predict(fc) plt.title("Random Forest") forest_prediction = np.rint(forest_prediction) #ATTENZIONE: CONVERTENDO IN INTERO PERDO LA PRECISIONE. print(forest_prediction) plt.plot(fc['time'], modelForest.predict(fc)) # timePred = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days = 1) # timeDelta = timedelta(hours = 1) # xTime = [] # xtime = np.asarray(xTime) # for i in range(24): # xTime.append(timePred+timeDelta*i) dtPrediction = pandas.DataFrame() dtPrediction.insert(0, 'id_webcam', table['id_webcam'].iloc[0:24]) dtPrediction.insert(1, 'city', table['city'].iloc[0:24]) dtPrediction.insert(2, 'location', table['location'].iloc[0:24]) dtPrediction.insert(3, 'latitude', table['latitude'].iloc[0:24]) dtPrediction.insert(4, 'longitude', table['longitude'].iloc[0:24]) dtPrediction.insert(5, 'numPeople', forest_prediction[0:24]) dtPrediction.insert(6, 'date', forecast['datetime'].iloc[0:24]) dtPrediction.insert(7, 'time', forecast['datetime'].iloc[0:24]) dtPrediction.insert(8, 'type', int(1)) dtPrediction.insert(9, 'weather_description', forecast['weather_description']) dtPrediction.insert(10, 'temperature', forecast['temperature']) dtPrediction.insert(11, 'day_of_week', fc['day_of_week']) print(dtPrediction) for i in range(24): Detection(id_webcam=dtPrediction['id_webcam'][i], city=dtPrediction['city'][i], location=dtPrediction['location'][i], latitude=dtPrediction['latitude'][i], longitude=dtPrediction['longitude'][i], numPeople=dtPrediction['numPeople'][i], date=dtPrediction['date'][i], time=dtPrediction['time'][i], type=dtPrediction['type'][i], weather_description=dtPrediction['weather_description'][i], temperature=dtPrediction['temperature'][i], day_of_week=dtPrediction['day_of_week'][i]).save()
#!/usr/bin/python3.5 import datetime today = datetime.date.today() print(today) crimedate = datetime.date(2013, 3, 30) print(crimedate) z = today - crimedate # type datetime.timedelta print(z) print(type(z)) # get days only instead of "1708 days, 0:00:00" print(z.days) date_format = "%m/%d/%Y" xxx = datetime.datetime.strptime('3/15/2012', date_format) datetime.combine(z, datetime.min.time()) #print(today-xxx)
def calculate_now(self) -> float: seconds_since_start = float((datetime.today() - datetime.combine(self.model.starting_date, time())).total_seconds()) return seconds_since_start / (3600.0 * float(self.config.graph['units'] / self.config.model['timedelta']))
def get_time_diff(self): # requested_at = datetime.datetime(Request.objects.filter(request_id=self.request_id).values('requested_at')) dt1 = datetime.combine(self.requested_at, self.t1) dt2 = datetime.combine(datetime.datetime.now(), self.t2) return timesince(dt1, dt2) # Assuming dt2 is the more recent time
def novo_chamado_hse(request): args = Perfil.objects.filter(user=request.user.username) print(args) if args.count() > 0: if request.method == 'POST': form = chamado_hseForm(request.POST) print (form.errors) if form.is_valid(): post = form.save(commit=False) Emp = empresa_terc.objects.filter(id=post.empresa_id)[0] post.setor_solicitante = request.POST.get('setor_solicitante') post.gestor_solicitante = request.POST.get('gestor_solicitante') post.fone_solicitante = request.POST.get('fone_solicitante') post.status = 'Aguardando Terceiro' post.tempo_estimado = request.POST.get('tempo_estimado') print(request.POST.get('tempo_estimado')) post.email_terc = Emp.email post.solicitante = request.user post.email_solicitante = request.user.email post.save() print(post.id) obj= chamado_hse.objects.get(id = post.id) log = logs(num_cham=str(obj.id), ator=request.user.username, acao= "Abertura Chamado", tipo="open") log.id = None log.save() data = datetime.strptime(request.POST.get('tempo_estimado'), '%m/%d/%Y') dt = datetime.combine(data, time(00, 00)) - timedelta(days=4) arr = [] dict = {} cont = 0 for x in request.POST.getlist('tipo_servico'): if x == '1': arr.insert(cont,'Trabalho em alta tensão e eletricidade') dict = {'CURSO DE ELETRICISTA':'Trabalho em alta tensão e eletricidade','ASO ALTA TENSÃO':'Trabalho em alta tensão e eletricidade','CURSO NR 10 OU RECICLAGEM':'Trabalho em alta tensão e eletricidade',} if x == '2': arr.insert(cont,'Trabalhos em altura') cont = cont + 1 dict.update({'CERTIFICADO TREINAMENTO NR35':'Trabalhos em altura','ASO TRABALHOS EM ALTURA':'Trabalhos em altura','FICHA DE EPI':'Trabalhos em altura',}) if x == '3': arr.insert(cont,'Espaços confinados') cont = cont + 1 dict.update({'CERTIFICADO TREINAMENTO DE VIGIA':'Espaços confinados','ASO ESPAÇO CONFINADO':'Espaços confinados','FICHA DE EPI':'Espaços confinados',}) if x == '4': arr.insert(cont,'Operação de empilhadeira') cont = cont + 1 dict.update({'ASO DA ADMISSÃO':'Operação de empilhadeira','CERTIFICADO OPERADOR EMPILHADEIRA':'Operação de empilhadeira',}) if x == '5': arr.insert(cont,'Trabalhos com plataformas elevatórias') cont = cont + 1 dict.update({'CURSO OPERADOR PLATAFORMA ELEVATÓRIA':'Trabalhos com plataformas elevatórias','ASO DA ADMISSÃO':'Trabalhos com plataformas elevatórias',}) if x == '6': arr.insert(cont,'Operação de guindaste ou munck') cont = cont + 1 dict.update({'CURSO DE GUINDASTE E/OU MUNCK':'Operação de guindaste ou munck','ASO DA ADMISSÃO':'Operação de guindaste ou munck','RINGGING PARA GUINDASTES':'Operação de guindaste ou munck',}) if x == '7': arr.insert(cont,'Trabalhador autônomo - Firma individual') cont = cont + 1 dict.update({'REGISTRO DA PREFEITURA':'Trabalhador autônomo - Firma individual','ASO':'Trabalhador autônomo - Firma individual','NÚMERO DE MATRÍCULA INSS':'Trabalhador autônomo - Firma individual',}) if x == '8': arr.insert(cont,'Assistência Técnica - mautenção') cont = cont + 1 dict.update({'CRACHÁ OU CARTEIRA PROFISSIONAL':'Assistência Técnica - mautenção','ASO':'Assistência Técnica - mautenção',}) if x == '9': arr.insert(cont,'Soldador') cont = cont + 1 dict.update({'PPRA DE SOLDA':'Soldador','COMPROVANTE DE CURSO OU EXPERIÊNCIA':'Soldador','FICHA DE EPI SOLDA':'Soldador',}) qx = empresa_terc.objects.all() context = { 'solicitante': request.user.username, 'emp': Emp.nome_empresa, 'nome_proj': request.POST.get('nome_proj'), 'data_term': dt, 'obs': request.POST.get('descricao'), 'dict':dict, 'arr':arr, 'obj':obj, 'emp_id': post.empresa_id, 'qx': qx, } message = EmailMessage('novo_chamEMAIL.html', context, settings.EMAIL_HOST_USER, [Emp.email,'*****@*****.**', '*****@*****.**',], render=True ) f = '/SIG_1.png' fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) message.attach(msg_img) message.send() return redirect('show_cham_sol', "None") else: form = chamado_hseForm() args = Perfil.objects.all() return render(request, 'novo_chamdo_hse.html', {'form': form, 'dado':args}) else: return redirect('perfil')
def UPLOAD_SCHEDULE(self): #loc= "schedule.xlsx" loc = filedialog.askopenfilename() wb = openpyxl.load_workbook(loc) sc = wb.active self.sc2 = sc rows = sc.max_row cols = sc.max_column self.sc_rows = rows self.sc_cols = cols recieved_Time = list() recieved_Route = list() recieved_AUTH = list() Train_Num = list() S_perBlock = list() S_real = list() Block_route = list() c = 0 T = list() holder = list() D = list() far = list() count = 0 meters_sep = 0 for i in range(2, rows): if (sc.cell(i, 32).value is not None and sc.cell(i, 7).value is not None): S_perBlock.append(sc.cell(i, 6).value) Block_route.append(sc.cell(i, 3).value) self.track_blocks.append(sc.cell(i, 3).value) if (count > 0): far.append(count + 1) meters_sep = 0 count = 0 slowest = S_perBlock[0] for t in range(0, len(S_perBlock)): if (slowest > S_perBlock[t]): slowest = S_perBlock[t] S_real.append(slowest) S_perBlock.clear() print(Block_route) self.routes.append(np.array(Block_route)) t1 = Block_route.pop() Block_route.clear() Block_route.append(t1) holder.append(sc.cell(i, 32).value) temp2 = str(sc.cell(i, 7).value) self.line_used.append(sc.cell(i, 1).value) self.sections.append(sc.cell(i, 2).value) D.append(temp2.strip()) Train_Num.append("Train 1") if (sc.cell(i, 32).value is None): count = count + 1 if (sc.cell(i, 4).value is not None): meters_sep = meters_sep + int(sc.cell(i, 4).value) Block_route.append(sc.cell(i, 3).value) self.track_blocks.append(sc.cell(i, 3).value) #print (sc.cell(i,4).value) self.sections.append(sc.cell(i, 2).value) self.line_used.append(sc.cell(i, 1).value) S_perBlock.append(sc.cell(i, 6).value) now = datetime.now() del holder[0] del Train_Num[0] initial = 0 stop = len(D) - 1 holdval = S_real for i in range(2, 11): if (i > 2): initial = checkpoint checkpoint = len(holder) S_real = S_real + holdval #calculate all of the time value for z in range(initial, checkpoint): Train_Num.append("Train " + str(i)) holder.append( (datetime.combine(now.date(), holder[z]) + timedelta(minutes=sc.cell(1, 43).value.minute, hours=sc.cell(1, 43).value.hour)).time()) #ONLY UPLOAD SCHEDULE FOR 1 TRAIN '''for i in range (0,len(D)-1): recieved_Route.append(str(D[i])+" -> "+str(D[i+1])) recieved_AUTH= recieved_AUTH+far''' for i in range(0, 10): for i in range(0, len(D) - 1): recieved_Route.append(str(D[i]) + " -> " + str(D[i + 1])) recieved_AUTH = recieved_AUTH + far #repeat the block # routes for all trains rep_len = len(self.routes) for i in range(0, 9): for z in range(0, rep_len): self.routes.append(self.routes[z]) #SORTING BY TIME for i in range(0, len(holder)): for z in range(0, len(holder) - 1): if (holder[z] > holder[z + 1]): switch = holder[z + 1] holder[z + 1] = holder[z] holder[z] = switch switch = recieved_Route[z + 1] recieved_Route[z + 1] = recieved_Route[z] recieved_Route[z] = switch switch = recieved_AUTH[z + 1] recieved_AUTH[z + 1] = recieved_AUTH[z] recieved_AUTH[z] = switch switch = Train_Num[z + 1] Train_Num[z + 1] = Train_Num[z] Train_Num[z] = switch switch = S_real[z + 1] S_real[z + 1] = S_real[z] S_real[z] = switch switch = self.routes[z + 1] self.routes[z + 1] = self.routes[z] self.routes[z] = switch for i in range(0, len(holder)): temp = str(holder[i]) T.append(temp[-8:-3]) #UPDATE SCHEDULE LIST BOXES self.l.delete(0, END) self.l2.delete(0, END) self.l3.delete(0, END) self.l4.delete(0, END) self.l5.delete(0, END) for i in range(0, len(Train_Num)): self.l.insert(i, Train_Num[i]) self.l2.insert(i, recieved_Route[i]) self.l3.insert(i, T[i]) self.l5.insert(i, recieved_AUTH[i]) self.l4.insert(i, S_real[i]) #UPDATE TRACK MODEL Track_Switches = list() for i in range(2, rows): if ("SWITCH" in str(sc.cell(i, 7).value).upper()): Track_Switches.append( str(sc.cell(i, 2).value) + str(sc.cell(i, 3).value) + "-" + str(sc.cell(i, 1).value)) self.l7.delete(0, END) self.l6.delete(0, END) self.switches.clear() for i in range(0, len(Track_Switches)): self.l7.insert(i, Track_Switches[i]) self.switches.insert(i, 0) #USER FEEDBACK import os title = "SYSTEM UPDATE" x = self.l7.curselection() message = "SCHEDULE AND TRACK MODEL SUCCESSFULLY UPDATED" command = f''' osascript -e 'display notification "{message}" with title "{title}"' ''' os.system(command)
def tomorrow(): d = date.today() + timedelta(days=1) t = time(0, 0) return datetime.combine(d, t)
def five_oclock(): mid = datetime.min.time() # midnight delta = timedelta(hours=5) # plus 5 hours five = (datetime.combine(date(1, 1, 1), mid) + delta).time() return five
time_stamp = time.time() print(time_stamp) # create a date from a timestamp date_stamp = date.fromtimestamp(time_stamp) print(date_stamp) # get components of a date print(date_stamp.year) print(date_stamp.month) print(date_stamp.day) # ------------------------- PART TWO -------------------------- from datetime import datetime, date, time # create a date and a time my_date = date(2019, 3, 22) my_time = time(12, 30) # create a datetime my_datetime = datetime.combine(my_date, my_time) print(my_datetime) # get the different components print(my_datetime.year) print(my_datetime.month) print(my_datetime.day) print(my_datetime.hour) print(my_datetime.minute)