def __init__(self, *args, **kwargs): super(StaffEvent, self).__init__(*args, **kwargs) for field in ['beginning', 'end', 'english_beginning', 'english_end']: self.fields[field] = date_input(self.fields[field]) if self.instance: if getattr(self.instance, "beginning"): beginning = getattr(self.instance, "beginning") beginning = beginning.astimezone(timezone('Asia/Tokyo')) self.fields["beginning_time"].initial = "%02d:%02d" % ( beginning.hour, beginning.minute) if getattr(self.instance, "end"): end = getattr(self.instance, "end") end = end.astimezone(timezone('Asia/Tokyo')) self.fields["end_time"].initial = "%02d:%02d" % (end.hour, end.minute) if getattr(self.instance, "english_beginning"): english_beginning = getattr(self.instance, "english_beginning") self.fields["english_beginning_time"].initial = "%02d:%02d" % ( english_beginning.hour, english_beginning.minute) if getattr(self.instance, "english_end"): english_end = getattr(self.instance, "english_end") self.fields["english_end_time"].initial = "%02d:%02d" % ( english_end.hour, english_end.minute) self.fields['image'].required = True
def get_record(request): if request.method == "GET": user_id = request.GET['user_id'] date = request.GET['date'] if date == "all": records = Record.objects.filter(user_id=user_id).values( 'start_time', 'end_time', 'round_mark') # query data else: records = Record.objects.filter(user_id=user_id, end_time__date=date).values( 'start_time', 'end_time', 'round_mark') # query data data = list(records) # Converts time from UTC to CST for i in range(0, len(data)): temp_time = data[i]['start_time'] data[i]['start_time'] = temp_time.astimezone( timezone(timedelta(hours=8))) temp_time = data[i]['end_time'] data[i]['end_time'] = temp_time.astimezone( timezone(timedelta(hours=8))) res = add_header(data) return res else: return HttpResponse('Wrong request type')
def get_transactions_today(self): today = datetime.date.today() today_min = datetime.datetime.combine(today, datetime.time.min) today_max = datetime.datetime.combine(today, datetime.time.max) today_min = today_min.replace(tzinfo=timezone('UTC')) today_max = today_max.replace(tzinfo=timezone('UTC')) return self.get_transactions().filter(timestamp__range=(today_min, today_max))
def filter_events(year, month, day=None, venue_pk=None, company_pk=None, timewindow_start=None, timewindow_end=None, max_price=None, classification=None): year = int(year) month = int(month) if day: day = int(day) date = datetime.date(year, month, day) print(date.strftime("Searching for events on %B %d, %Y.")) events = Event.objects.filter(date_and_time__year=date.year, date_and_time__month=date.month, date_and_time__day=date.day) else: date = datetime.date(year, month, 1) print(date.strftime("Searching for events in %B, %Y.")) events = Event.objects.filter(date_and_time__year=date.year, date_and_time__month=date.month) print("Found {}.".format(', '.join([str(e) for e in events]))) # Filter on Venue if venue_pk: venue = Venue.objects.get(pk=venue_pk) events = events.filter(venue=venue) # Filter on Company if company_pk: company = Company.objects.get(pk=company_pk) events = events.filter(company=company) # Filter on timewindow if timewindow_start: start_time = timezone(year, month, day, timewindow_start) events = events.filter(date_and_time__gte=start_time) if timewindow_end: end_time = timezone(year, month, day, timewindow_end) events = events.filter(date_and_time__lte=end_time) # Filter on price if max_price: events = events.filter(ticket_price__lte=int(max_price)) # Filter on company classification if classification: events = events.filter(company__classification=classification) return events
def save(self, commit=True): instance = super(StaffEvent, self).save(commit=False) # set some reasonable defaults for EN/JP start/end times # (must be in the server's appropriate localtime) beginning_hour_jst = 16 beginning_minute_jst = 0 end_hour_jst = 15 end_minute_jst = 0 # beginning_hour_utc = 9 beginning_minute_utc = 0 end_hour_utc = 8 end_minute_utc = 0 # beginning_time = self.cleaned_data['beginning_time'] beginning_hour_jst = beginning_time.hour beginning_minute_jst = beginning_time.minute end_time = self.cleaned_data['end_time'] end_hour_jst = end_time.hour end_minute_jst = end_time.minute if self.cleaned_data['english_beginning_time']: english_beginning_time = self.cleaned_data[ 'english_beginning_time'] beginning_hour_utc = english_beginning_time.hour beginning_minute_utc = english_beginning_time.minute if self.cleaned_data['english_end_time']: english_end_time = self.cleaned_data['english_end_time'] end_hour_utc = english_end_time.hour end_minute_utc = english_end_time.minute instance.beginning = instance.beginning.astimezone( timezone('Asia/Tokyo')).replace( hour=beginning_hour_jst, minute=beginning_minute_jst).astimezone(timezone('UTC')) instance.end = instance.end.astimezone(timezone('Asia/Tokyo')).replace( hour=end_hour_jst, minute=end_minute_jst).astimezone(timezone('UTC')) if getattr(instance, "english_beginning"): instance.english_beginning = instance.english_beginning.replace( hour=beginning_hour_utc, minute=beginning_minute_utc) if getattr(instance, "english_end"): instance.english_end = instance.english_end.replace( hour=end_hour_utc, minute=end_minute_utc) for field in ['romaji_name', 'english_name']: if not getattr(instance, field): setattr(instance, field, None) if commit: instance.save() return instance
def CurrentMonthView(request): try: now = datetime.datetime.now() year = now.year month = now.month next_month = month+1 st = timezone('Asia/Shanghai').localize(datetime.datetime(year, month, 1, 0,0,0)) et = timezone('Asia/Shanghai').localize(datetime.datetime(year, next_month, 1, 0,0,0)) sync(st, et) current_month_appointment = Appointment.objects.filter(start_time__range = (timezone('Asia/Shanghai').localize(datetime.datetime(year, month, 1, 0,0,0)), timezone('Asia/Shanghai').localize(datetime.datetime(year, next_month, 1, 0,0,0)))) template_name ='booking_calendar/home.html' selected_period_items = serializers.serialize("json", current_month_appointment) except Appointment.DoesNotExist: raise Http404 ("Appointment does not exist") return render(request, template_name, {'selected_period_items': selected_period_items})
def wsdetailrequest(request,requestid): delrequestlist = DeliveryRequest.objects.filter(tracking_number=requestid) if delrequestlist.count(): delrequest = delrequestlist.first() requestbill = delrequest.bill #try catch excepcion requeststatuslist = delrequest.status_set if requeststatuslist.count(): requeststatus = requeststatuslist.first() if requeststatus.status == '00': stat = 'Recibido' elif requeststatus.status == '01': stat = 'Por despachar' elif requeststatus.status == '02': stat = 'Despachada' elif requeststatus.status == '03': stat = 'Entregada' #root = etree.XML('\\<?xml version="1.0"?>') #main = etree.ElementTree(root) dispatch = etree.Element('despacho') answer = etree.SubElement(dispatch, 'respuesta') etree.SubElement(answer,'costo').text = str(requestbill.total) etree.SubElement(answer,'fechaEntrega').text = str( (delrequest.delivery_date.astimezone(timezone('America/Caracas'))).strftime('%d-%m-%Y %H:%M')) etree.SubElement(answer,'tracking').text = str(delrequest.tracking_number) etree.SubElement(answer,'estado').text = str(stat) delrequestxml = etree.tostring(dispatch, pretty_print=True) return HttpResponse(delrequestxml,content_type='application/xml') #return HttpResponse(xmlbill(delrequest),content_type='application/xml') else: HttpResponse(status=400) else: return HttpResponse('No existe la solicitud.',content_type='text/plain')
def get_queryset(self): """ Return the last five published questions(not including those set to be published in the future). """ return Question.objects.filter( pub_date_lte=timezone() ).order_by('-pub_date')[:5]
def FillDb(csv_file_path): '''fills the db with the data from the lan desk report''' users = GetCsv(csv_file_path) cen_tz = timezone('America/Chicago') time_format = "%m/%d/%y %H:%M" for user in users: '''in get or create it returns two values fist is the object second is the bool if it existed''' try: vendor, created = Vendor.objects.get_or_create(vendor=user['Company'].strip().lower()) #adnames u, created = User.objects.get_or_create(email=user['EmailAddress'].strip().lower(),vendor=vendor) u.first_name = user['GivenName'].strip().capitalize() u.last_name = user['Surname'].strip().capitalize() u.email = user['EmailAddress'].strip().lower() u.phone = user['OfficePhone'] if (user['PasswordExpired'] == 'TRUE' or user['Enabled'] == 'False'): u.account_active = False else: u.account_active = True u.pass_last_set = cen_tz.localize(datetime.strptime(user['PasswordLastSet'], time_format)) u.user_name = user['SamAccountName'].strip().capitalize() u.pass_last_set = u.save() except: print("could not save " +user['GivenName'] + " " + user['Surname'].strip().capitalize() + " "+user['EmailAddress'].strip().lower() )
async def chat_message(self, event): try: body = event['message'] sender = get_user_model().objects.get(pk=int(event['name'])) user_profile = UserProfile.objects.get(user__id=int(event['name'])) await self.send(text_data=json.dumps({ 'type': 'chat_message', 'body': body, 'name': sender.name, 'sender': sender.id, 'create_at': str( parser.parse(event['create_at']).astimezone( timezone('Asia/Tokyo'))), 'profile_image': str(user_profile.profile_image.url), 'talk_room_id': self.room_group_name, })) except Exception as e: raise
def create_question(question_text, days): """ Create a question with tue given 'question_text' and published the given number of 'days' offset to now (negative for questions that have yet to be published). """ time = timezone() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time)
def chart(request): # tz = timezone('Asia/Seoul') tz = timezone(settings.TIME_ZONE) jobs = Job.objects.order_by('start').order_by('lineno') job_dict = defaultdict(lambda: []) for job in jobs: job_dict[job.lineno].append(job) linenos = job_dict.keys() linenos = sorted(linenos) height = len(linenos) * 150 data = [] for lineno in linenos: item = {'category': lineno, 'segments': []} jobs = job_dict[lineno] for job in jobs: segment = { 'lotno': job.lotno, 'color': job.color, "colorname": job.colorname, "qty": job.qty, "start": job.start.astimezone(tz).strftime('%Y-%m-%d-%H'), "end": job.finish.astimezone(tz).strftime('%Y-%m-%d-%H') } item['segments'].append(segment) data.append(item) return render(request, 'scheduler/chart.html', { 'chart_data': data, 'chart_height': height })
def driver_get_revenue(request): # Get token access_token = AcessToke.objects.get(token=request.GET.get("access_token"), expires__gt=timezone.now()) driver = access_token.user.driver from datetime import timedelta revenue = {} today = timezone.now() current_weekdays = [ today + timezone(days=i) for i in range(0 - today.weekday(), 7 - today.weekday()) ] for day in current_weekdays: orders = Order.objects.filter( driver=driver, status=Order.DELIVERED, created_at__year=day.year, created_at__month=day.month, created_at__day=day.day, ) revenue[day.strftime["%a"]] = sum(order.total for order in orders) return JsonResponse({"revenue": revenue})
def local_time(self): """ Get local time by timezone from geo info """ if self.time_zone: tzone = timezone(self.time_zone) local_time = datetime.now(tzone) else: local_time = datetime.now() return local_time.strftime('%H:%M')
def test_was_published_recently_with_future_question(self): ''' was_published_recently() returns False for questions whose pub_date is in the future. ''' time = timezone().now() + datetime.timedelta(days=30) future_question = Question(pub_date) self.assertIs(future_question.was_published_recently(), False)
def dashboard(request): if request.method == 'POST': user = request.user utc_time = datetime.now(timezone('UTC')) posts = Post.objects.filter(user=user) upcoming = posts.filter(posttime__gte=utc_time).order_by('posttime') recent = posts.filter(posttime__lte=utc_time).order_by('-posttime')[:9] form = NewPost(request.POST, request.FILES, user=user) if form.is_valid(): tz = str(tzlocal.get_localzone()) dd = form.cleaned_data.get('sched_date') #datetime.date object t = form.cleaned_data.get('sched_time') #time string from form tt = datetime.strptime(t, '%H:%M:%S').time() #datetime.time object c = datetime.combine(dd, tt) #combined datetime naive object cloc = timezone(tz).localize(c) #assign to local timezone cutc = cloc.astimezone(timezone('UTC')) #convert to UTC timezone new_post = form.save(commit=False) new_post = Post.objects.create ( text = form.cleaned_data.get('text'), media = form.cleaned_data.get('media'), sched_date = cloc.strftime('%Y-%m-%d'), sched_time = cloc.strftime('%-I:%M %p'), account = form.cleaned_data.get('account'), user = request.user, posttime = cutc ) new_post.save() form = NewPost() return redirect('dashboard') else: user = request.user utc_time = datetime.now(timezone('UTC')) posts = Post.objects.filter(user=user) upcoming = posts.filter(posttime__gte=utc_time).order_by('posttime') recent = posts.filter(posttime__lte=utc_time).order_by('-posttime')[:9] form = NewPost(user=user) return render(request, 'dashboard.html', {'upcoming': upcoming, 'recent': recent, 'form': form})
def validate(self, data): user = get_user_model().objects.filter(otp_code=data['otp_code']) if not user.exists(): return Response({'errors': 'Please Provide a valid otp'}) expiry_time = user[0].otp_code_expiry if expiry_time > timezone(): return Response({'otp': data['otp_code']}) return Response({'errors': 'OTP provided has expired'})
def tz_aware_datetime(datetime_obj, time_zone=None): if settings.USE_TZ: if time_zone is None: try: time_zone = timezone(settings.TIME_ZONE) except: time_zone = timezone.utc else: time_zone = timezone(time_zone) if datetime_obj.tzinfo is None or datetime_obj.tzinfo.utcoffset( datetime_obj) is None: datetime_with_tz = timezone.utc.localize(datetime_obj) else: datetime_with_tz = datetime_obj return datetime_with_tz.astimezone(time_zone) return datetime_obj
def dateByUTC(KST): if (UTC.tzinfo == timezone(TIME_ZONE)): timeDiffrence = datetime.timedelta(hours=-9) UTC = datetime.timezone(datetime.timedelta(hours=0)) localeTime = KOR.replace(tzinfo=UTC) + timeDiffrence return localeTime # TO UTC else: return KST
def save(self, commit=True): instance = super(StaffEvent, self).save(commit=False) # set some reasonable defaults for EN/JP start/end times # (must be in the server's appropriate localtime) beginning_hour_jst = 16 beginning_minute_jst = 0 end_hour_jst = 15 end_minute_jst = 0 # begining_hour_utc = 9 begining_minute_utc = 0 end_hour_utc = 8 end_minute_utc = 0 # beginning_time = self.cleaned_data['beginning_time'] beginning_hour_jst = beginning_time.hour beginning_minute_jst = beginning_time.minute end_time = self.cleaned_data['end_time'] end_hour_jst = end_time.hour end_minute_jst = end_time.minute if self.cleaned_data['english_beginning_time']: english_beginning_time = self.cleaned_data['english_beginning_time'] beginning_hour_utc = english_beginning_time.hour beginning_minute_utc = english_beginning_time.minute if self.cleaned_data['english_end_time']: english_end_time = self.cleaned_data['english_end_time'] end_hour_utc = english_end_time.hour end_minute_utc = english_end_time.minute instance.beginning = instance.beginning.astimezone(timezone('Asia/Tokyo')).replace(hour=beginning_hour_jst, minute=beginning_minute_jst).astimezone(timezone('UTC')) instance.end = instance.end.astimezone(timezone('Asia/Tokyo')).replace(hour=end_hour_jst, minute=end_minute_jst).astimezone(timezone('UTC')) if getattr(instance, "english_beginning"): instance.english_beginning = instance.english_beginning.replace(hour=beginning_hour_utc, minute=beginning_minute_utc) if getattr(instance, "english_end"): instance.english_end = instance.english_end.replace(hour=end_hour_utc, minute=end_minute_utc) for field in ['romaji_name', 'english_name']: if not getattr(instance, field): setattr(instance, field, None) if commit: instance.save() return instance
def request_logs(request): query = Request.objects.order_by('-time')[:10].values() c = {'requests': list(query)} if request.method == 'POST': body = request.body.decode('utf-8') date = json.loads(body)['date'] date = datetime.strptime( date, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone(timedelta(0))) query = Request.objects.filter(time__gte=date).values() c = {'requests': list(query)} return JsonResponse(c) return render(request, 'iho/logs.html', c)
def __init__(self, *args, **kwargs): super(StaffEvent, self).__init__(*args, **kwargs) for field in ['beginning', 'end', 'english_beginning', 'english_end']: self.fields[field] = date_input(self.fields[field]) if self.instance: if getattr(self.instance, "beginning"): beginning = getattr(self.instance, "beginning") beginning = beginning.astimezone(timezone('Asia/Tokyo')) self.fields["beginning_time"].initial = "%02d:%02d" % (beginning.hour, beginning.minute) if getattr(self.instance, "end"): end = getattr(self.instance, "end") end = end.astimezone(timezone('Asia/Tokyo')) self.fields["end_time"].initial = "%02d:%02d" % (end.hour, end.minute) if getattr(self.instance, "english_beginning"): english_beginning = getattr(self.instance, "english_beginning") self.fields["english_beginning_time"].initial = "%02d:%02d" % (english_beginning.hour, english_beginning.minute) if getattr(self.instance, "english_end"): english_end = getattr(self.instance, "english_end") self.fields["english_end_time"].initial = "%02d:%02d" % (english_end.hour, english_end.minute) self.fields['image'].required = True
def edit_post(request, pk): edit_post = get_object_or_404(Post, pk=pk) if request.method == 'POST': user = edit_post.user utc_time = datetime.now(timezone('UTC')) posts = Post.objects.filter(user=user) upcoming = posts.filter(posttime__gte=utc_time).order_by('posttime') recent = posts.filter(posttime__lte=utc_time).order_by('-posttime')[:9] form = NewPost(request.POST, request.FILES, instance=edit_post) if form.is_valid(): tz = str(tzlocal.get_localzone()) edit_post = form.save(commit=False) edit_post.user = edit_post.user dd = edit_post.sched_date t = edit_post.sched_time tt = datetime.strptime(t, '%H:%M:%S').time() c = datetime.combine(dd, tt) cloc = timezone(tz).localize(c) edit_post.sched_date = cloc.strftime('%Y-%m-%d') edit_post.sched_time = cloc.strftime('%I:%M %p') edit_post.posttime = cloc.astimezone(timezone('UTC')) edit_post.save() form = NewPost() return redirect('dashboard') else: user = request.user utc_time = datetime.now(timezone('UTC')) posts = Post.objects.filter(user=user) upcoming = posts.filter(posttime__gte=utc_time).order_by('posttime') recent = posts.filter(posttime__lte=utc_time).order_by('-posttime')[:9] form = NewPost(instance=edit_post) edit = "edit" return render(request, 'dashboard.html', {'upcoming': upcoming, 'recent': recent, 'form': form, 'edit': edit})
def put(self,request,activity_id, year,month,day,hr,minute,sec): eastern = timezone('US/Eastern') end_time = datetime.datetime(year,month,day,hr,minute,sec) end_time = eastern.localize(end_time) this_activity = activity.objects.get(id=activity_id) this_activity.end_time = end_time #also set the total time as the differnece of the start time and end time total_time = end_time - this_activity.start_time this_activity.total_time = total_time this_activity.save() return Response('activity updated', status.HTTP_200_OK )
def get_all_user_details(self, request): from pytz import timezone response = { "ok": False, 'members': [], "message": '!!! Ops something went wrong ' } status_code = status.HTTP_400_BAD_REQUEST data = list() all_members = UserData.objects.all() for member in all_members: member_details = { 'id': member.id, 'real_name': member.real_name, 'tz': member.time_zone, 'activity_periods': [] } for activity in member.activity_periods.all(): activity_data = { 'start_time': activity.start_time.astimezone( timezone((member_details['tz'] ))).strftime("%d %B, %Y, %I%p "), 'end_time': activity.end_time.astimezone( timezone((member_details['tz'] ))).strftime("%d %B, %Y, %I%p ") } member_details['activity_periods'].append(activity_data) data.append(member_details) if len(data) > 0: response.update({'members': data, 'ok': True}) response.update({'message': 'data recived from db '}) status_code = status.HTTP_200_OK return Response(response, status=status_code)
def set_scheduled_date(self): if not self.message.scheduled: self.scheduled_date = timezone.now() else: if self.message.scheduled_date_type == 1: # Use sender's timezone local_tz = self.message.sender.tz_obj() else: # Use recipient's timezone, or Melbourne time if user timezone unknown if self.user: local_tz = self.user.tz_obj() else: local_tz = timezone('Australia/Melbourne') self.scheduled_date = local_tz.localize(self.message.scheduled_date.replace(tzinfo=None))
def set_scheduled_date(self): if not self.message.scheduled: self.scheduled_date = timezone.now() else: if self.message.scheduled_date_type == 1: # Use sender's timezone local_tz = self.message.sender.tz_obj() else: # Use recipient's timezone, or Melbourne time if user timezone unknown if self.user: local_tz = self.user.tz_obj() else: local_tz = timezone('Australia/Melbourne') self.scheduled_date = local_tz.localize( self.message.scheduled_date.replace(tzinfo=None))
def matchup_finished(request): timenow = datetime.datetime.now().replace(tzinfo=timezone('US/Eastern')) matchups = Matchup.objects.filter(league = 'NFL',date__lte = timenow, game_completed = 'No') for matchup in matchups: week = 4 kind = 'REG' year = 2015 game = nflgame.one(year,week=week,kind=kind,away=matchup.away_team.city_id, home=matchup.home_team.city_id) if game: print game.away if game.game_over(): matchup.away_score = game.score_away matchup.home_score = game.score_home matchup.game_completed = "Yes" matchup.save() return redirect('/picks/adminfun')
def post(self, request): # current format of data sent = {'habit_id':newHabit.id,'start_time': datetime.datetime.now(), 'end_time': datetime.datetime.now(), 'total_time':0} data = request.data id_num = data['habit_id'] habit_object = Habit.objects.get(id = id_num) del data['habit_id'] data['habit'] = habit_object eastern = timezone('US/Eastern') newDate = datetime.datetime.now() newDate = eastern.localize(newDate) data['start_time'] = newDate newActivity = activity.objects.create(**data) newActivity.save() if (newActivity): return Response('activity created', status.HTTP_201_CREATED) else: return Response('error', status.HTTP_400_BAD_REQUEST)
class New(models.Model): Title = models.CharField(max_length=50) Text = HTMLField() Date = models.DateTimeField(editable=False, default=datetime.now(timezone('Asia/Omsk'))) Group = models.ManyToManyField('GP', blank=True, null=True) def __str__(self): return self.Title def get_text(self): return self.Text def get_date(self): return self.Date.date() def get_id(self): return self.id.__str__()
def api_add_followup(request): data = JSONParser().parse(request) data['followed_by'] = request.user.id serializer = FollowUpSerializer(data=data) if serializer.is_valid(): serializer.save() # not we need to update the followeup_date for lead object lead = Lead.objects.filter(id=data["lead"])[0] from datetime import datetime from pytz import timezone tz=timezone(request.user.studiouser.studio_id.timezone) followupdate = datetime.strptime(data["followed_date"],'%m/%d/%Y %I:%M %p') lead.nextfollowupdate = tz.localize(followupdate) #lead.nextfollowupdate = datetime.strptime(data["followed_date"],'%m/%d/%Y %I:%M %p') #lead.nextfollowupdate = lead.nextfollowupdate.replace(tzinfo=timezone(request.user.studiouser.studio_id.timezone)) lead.save() return JSONResponse(serializer.data, status=200) else: print "data is not valid, hence returning", serializer.errors return JSONResponse(serializer.errors, status=400)
class TaskLogDetail(models.Model): child_of_task = models.ForeignKey('TaskLog') bind_host = models.ForeignKey('BindHostToUser') #default=datetime.now().replace(tzinfo=utc) #date = models.DateTimeField(auto_now_add=True) #finished date date = models.DateTimeField(default=datetime.now().replace( tzinfo=timezone("UTC"))) event_log = models.TextField() result_choices = (('success', 'Success'), ('failed', 'Failed'), ('unknown', 'Unknown')) result = models.CharField(choices=result_choices, max_length=30, default='unknown') note = models.CharField(max_length=100, blank=True) def __unicode__(self): return "child of:%s result:%s" % (self.child_of_task.id, self.result) class Meta: verbose_name = u'批量任务日志' verbose_name_plural = u'批量任务日志'
def update_and_tweets(request): """ This will update or tweet depending on the time """ logger.info('Updating the list of jobs') from datetime import datetime, timedelta, time from pytz import timezone ottawa_timezone = timezone('America/Montreal') ottawa_now = datetime.now(ottawa_timezone) now_time = ottawa_now.time() #tweet_time = False#now_time >= time(5,30) and now_time <= time(18,30) upgrade_time = True# now_time >= time(17,00) and now_time <= time(19,30) if upgrade_time: res = process_it() #Update the list of jobs from Open Data portal (Ottawa.open.data) logger.info('yes we added new jobs') return redirect("/") else: logger.info("no we didn't have new jobs in full.jsonr") return redirect("/")
def wsdetailrequest(request, requestid): delrequestlist = DeliveryRequest.objects.filter(tracking_number=requestid) if delrequestlist.count(): delrequest = delrequestlist.first() requestbill = delrequest.bill #try catch excepcion requeststatuslist = delrequest.status_set if requeststatuslist.count(): requeststatus = requeststatuslist.first() if requeststatus.status == '00': stat = 'Recibido' elif requeststatus.status == '01': stat = 'Por despachar' elif requeststatus.status == '02': stat = 'Despachada' elif requeststatus.status == '03': stat = 'Entregada' #root = etree.XML('\\<?xml version="1.0"?>') #main = etree.ElementTree(root) dispatch = etree.Element('despacho') answer = etree.SubElement(dispatch, 'respuesta') etree.SubElement(answer, 'costo').text = str(requestbill.total) etree.SubElement(answer, 'fechaEntrega').text = str( (delrequest.delivery_date.astimezone( timezone('America/Caracas'))).strftime('%d-%m-%Y %H:%M')) etree.SubElement(answer, 'tracking').text = str(delrequest.tracking_number) etree.SubElement(answer, 'estado').text = str(stat) delrequestxml = etree.tostring(dispatch, pretty_print=True) return HttpResponse(delrequestxml, content_type='application/xml') #return HttpResponse(xmlbill(delrequest),content_type='application/xml') else: HttpResponse(status=400) else: return HttpResponse('No existe la solicitud.', content_type='text/plain')
def import_org_list(): # open the csv we want to read my_target_data_file = os.path.join(settings.BASE_DIR, 'ihub', 'orgs.csv') with open(my_target_data_file, 'r') as csv_read_file: my_csv = csv.DictReader(csv_read_file) # stuff that has to happen before running the loop for row in my_csv: # first step: make sure there are no duplicate names org, created = ml_models.Organization.objects.get_or_create( name_eng=row["name_eng"]) # add the region # check the province in order to determine the region region = shared_models.Region.objects.get( name__icontains="pacific") for r in org.regions.all(): org.regions.remove(r) org.regions.add(region) # add the grouping if "first nation" in row["Grouping"].lower(): grouping = ml_models.Grouping.objects.filter( name__icontains="First Nation / Community").first() else: grouping, created = ml_models.Grouping.objects.get_or_create( name=row["Grouping"]) if not grouping.is_indigenous: grouping.is_indigenous = True grouping.save() for g in org.grouping.all(): org.grouping.remove(g) org.grouping.add(grouping) # add the normal attrs org.name_ind = nz(row["name_ind"], None) org.abbrev = nz(row["abbrev"], None) org.address = nz(row["address"], None) org.mailing_address = nz(row["mailing_address"], None) org.city = nz(row["city"], None) org.postal_code = nz(row["postal_code"], None) org.province_id = row["province"] org.phone = nz(row["phone"], None) org.fax = nz(row["fax"], None) org.dfo_contact_instructions = nz(row["dfo_contact_instructions"], None) org.notes = nz(row["notes"], None) org.key_species = nz(row["key_species"], None) org.former_name = nz(row["former_name"], None) org.website = nz(row["website"], None) org.council_quorum = nz(row["council_quorum"], None) org.election_term = nz(row["election_term"], None) date = None if row["next_election"]: date = make_aware( datetime.datetime.strptime(row["next_election"] + " 12:00", "%m/%d/%Y %H:%M"), timezone("Canada/Central")) org.next_election = date date = None if row["new_coucil_effective_date"]: date = make_aware( datetime.datetime.strptime( row["new_coucil_effective_date"] + " 12:00", "%m/%d/%Y %H:%M"), timezone("Canada/Central")) org.new_coucil_effective_date = date org.population_on_reserve = nz(row["population_on_reserve"], None) org.population_off_reserve = nz(row["population_off_reserve"], None) org.population_other_reserve = nz(row["population_other_reserve"], None) org.fin = nz(row["fin"], None) org.processing_plant = nz(row["processing_plant"], 0) try: org.save() except Exception as e: print(org, e)
u.pass_last_set = cen_tz.localize(datetime.strptime(user['PasswordLastSet'], time_format)) u.user_name = user['SamAccountName'].strip().capitalize() u.pass_last_set = u.save() except: print("could not save " +user['GivenName'] + " " + user['Surname'].strip().capitalize() + " "+user['EmailAddress'].strip().lower() ) FillDb(csv_file_path) users = GetCsv(csv_file_path) user = users[3] vendor, created = Vendor.objects.get_or_create(vendor=user['Company'].strip().lower()) cen_tz = timezone('America/Chicago') time_format = "%m/%d/%y %H:%M" vendor, created = Vendor.objects.get_or_create(vendor=user['Company'].strip().lower()) #adnames u, created = User.objects.get_or_create(email=user['EmailAddress'].strip().lower(),vendor=vendor) u.first_name = user['GivenName'].strip().capitalize() u.last_name = user['Surname'].strip().capitalize() u.email = user['EmailAddress'].strip().lower() u.phone = user['OfficePhone'] if (user['PasswordExpired'] == 'TRUE' or user['Enabled'] == 'False'): u.account_active = False else: u.account_active = True u.pass_last_set = cen_tz.localize(datetime.strptime(user['PasswordLastSet'], time_format)) u.user_name = user['SamAccountName'].strip().capitalize()
from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone # Create your models here. from pytz import timezone from datetime import datetime buenos_aires = timezone('America/Argentina/Buenos_Aires') class Expense(models.Model): fecha = models.DateField(default=datetime.now(buenos_aires).replace(tzinfo=None)) descripcion = models.CharField(max_length =100) precio = models.FloatField() extraordinario = models.IntegerField(choices = ((1, ("Si")),(0, ("No"))),default=0) class Meta: ordering = ['-id'] def get_absolute_url(self): return reverse('expense-detail', kwargs={'pk': self.pk})
def xmlbill(billreq): try: delreqbill = Bill.objects.get(pk=billreq) except Bill.DoesNotExist: print 'No existe la factura o la solicitud de envio' except MultipleObjectsReturned: print 'Existen varias facturas que coiniciden con la solicitud de envio' else: delreq = delreqbill.request #print 'Factura: ' + str(delreqbill) factura = etree.Element('factura') etree.SubElement(factura,'idFactura').text = str(delreqbill.pk) actores = etree.SubElement(factura,'actores') emisor = etree.SubElement(actores,'emisor') etree.SubElement(emisor,'rifEmisor').text = str(delreqbill.dist_rif) etree.SubElement(emisor,'nombreEmisor').text = str(delreqbill.dist_name) etree.SubElement(emisor,'cuenta').text = str(delreqbill.account_number) pagador = etree.SubElement(actores,'pagador') etree.SubElement(pagador,'rifPagador').text = str(delreq.associated_comm.rif) etree.SubElement(pagador,'nombrePagador').text = str(delreq.associated_comm.assoc_name) despachos = etree.SubElement(factura,'despachos') despacho = etree.SubElement(despachos,'despacho') productos = etree.SubElement(despacho,'productos') packagelist = delreq.package_set.all() for packageunit in packagelist: producto = etree.SubElement(productos,'producto') etree.SubElement(producto,'id').text = str(packageunit.pk) etree.SubElement(producto,'nombre').text = str(packageunit.description) etree.SubElement(producto,'cantidad').text = str(packageunit.amount) medidas = etree.SubElement(producto,'medidas') etree.SubElement(medidas,'peso').text = str(packageunit.weigth) etree.SubElement(medidas,'largo').text = str(packageunit.length) etree.SubElement(medidas,'ancho').text = str(packageunit.width) etree.SubElement(medidas,'alto').text = str(packageunit.height) #print packageunit etree.SubElement(despacho,'tracking').text = str(delreq.tracking_number) etree.SubElement(despacho,'costo').text = str(delreqbill.total) costos = etree.SubElement(factura,'costos') etree.SubElement(costos,'subtotal').text = str(delreqbill.sub_total) etree.SubElement(costos,'impuestos').text = str(delreqbill.taxes) etree.SubElement(costos,'total').text = str(delreqbill.total) fechas = etree.SubElement(factura,'fechas') etree.SubElement(fechas,'fechaEmision').text = str(delreqbill.issuance_date.astimezone(timezone('America/Caracas')).strftime('%d-%m-%Y %H:%M')) etree.SubElement(fechas,'fechaVencimiento').text = str(delreqbill.expiration_date.astimezone(timezone('America/Caracas')).strftime('%d-%m-%Y %H:%M')) if delreqbill.payment_date: paymentdate = delreqbill.payment_date.astimezone(timezone('America/Caracas')).strftime('%d-%m-%Y %H:%M') else: paymentdate = delreqbill.payment_date etree.SubElement(fechas,'fechaPago').text = str(paymentdate) statuses = etree.SubElement(factura,'statuses') statuslist = delreq.status_set.all() for statusunit in statuslist: date = statusunit.status_date.astimezone(timezone('America/Caracas')).strftime('%d-%m-%Y %H:%M') if statusunit.status == '00': stat = 'Recibido' elif statusunit.status == '01': stat = 'Por despachar' elif statusunit.status == '02': stat = 'Despachada' elif statusunit.status == '03': stat = 'Entregada' etree.SubElement(statuses,'status').text = date + ' ' + stat return etree.tostring(factura, pretty_print=True)
def wsnewrequest(request): if request.method == 'POST': conttype = request.META['CONTENT_TYPE'] if conttype == 'application/xml': xmlrequest = request.body dtdstring = StringIO.StringIO('<!ELEMENT despacho (id,comercio,productos,datosEnvio)><!ELEMENT id (#PCDATA)><!ELEMENT comercio (rif,nombre)><!ELEMENT rif (#PCDATA)><!ELEMENT nombre (#PCDATA)><!ELEMENT productos (producto+)><!ELEMENT producto (id,nombre,cantidad,medidas)><!ELEMENT id (#PCDATA)><!ELEMENT nombre (#PCDATA)><!ELEMENT cantidad (#PCDATA)><!ELEMENT medidas (peso,largo,ancho,alto)><!ELEMENT peso (#PCDATA)><!ELEMENT largo (#PCDATA)><!ELEMENT ancho (#PCDATA)><!ELEMENT alto (#PCDATA)><!ELEMENT datosEnvio (nombreDestinatario,telefonos,direccion,zip,ciudad,pais)><!ELEMENT nombreDestinatario (#PCDATA)><!ELEMENT telefonos (telefonoContacto+)><!ELEMENT telefonoContacto (#PCDATA)><!ELEMENT direccion (#PCDATA)><!ELEMENT zip (#PCDATA)><!ELEMENT ciudad (#PCDATA)><!ELEMENT pais (#PCDATA)>') dtd = etree.DTD(dtdstring) root = etree.XML(xmlrequest) if dtd.validate(root): associated = root[1] #print associated[0].text + ' ' + associated[1].text assoc_found = Associated.objects.filter(rif=associated[0].text,assoc_name=associated[1].text) if assoc_found.count() == 1: associated_comm = assoc_found.first() delcity = root[3][4].text delcountry = root[3][5].text delzip = root[3][3].text #Ruta destino locfound = Location.objects.filter(city=delcity,country=delcountry,zip_code=delzip) if locfound.count(): location = locfound.first() else: location = Location(city=delcity,state=delcity,country=delcountry,zip_code=delzip) location.save() routefound = Route.objects.filter(destination=location) if routefound.count(): route = routefound.first() else: route = Route(destination=location,charge_x_km=random.randrange(10,100,5)) route.save() #Solicitud de envio dllist = DeliveryRequest.objects.order_by('id') lastdl = dllist[dllist.count()-1] number = 10000 + lastdl.id + 1 tracking_number = (delcountry[0] + delcountry[1]).upper() + delzip.upper() + str(number) #print tracking_number daystodel = random.randrange(1,5,1) delivery_date = (datetime.utcnow()+timedelta(days=daystodel)).replace(tzinfo=utc) #print daystodel #print delivery_date address = root[3][2].text additional_info = 'Destinatario: ' + root[3][0].text + '\n' for telephone in root[3][1]: additional_info = additional_info + 'Teléfono: ' + telephone.text + '\n' #print additional_info newdelrequest = DeliveryRequest( tracking_number=tracking_number, delivery_date=delivery_date, address=address, additional_info=additional_info, route=route, associated_comm=associated_comm) newdelrequest.save() locationfound = Location.objects.filter( city='Distribución', state='Distribución', country='Distribución', zip_code='Distribución') if locationfound.count(): location = locationfound.first() else: location = Location(city='Distribución',state='Distribución',country='Distribución',zip_code='Distribución') location.save() #Estado de solicitud de envio newstatus = Status( status='00', location=location, delrequest=newdelrequest) newstatus.save() sub_total = 0 #Paquetes vinculados a la solicitud for product in root[2]: description = product[1].text amount =int(product[2].text) weigth = product[3][0].text length = product[3][1].text width = product[3][2].text height = product[3][3].text price = (((float(length)*float(width)*float(height))/166)*route.charge_x_km) newpackage = Package( amount=amount, weigth=weigth, length=length, width=width, height=height, description=description, delivery_req=newdelrequest, price=price) #print description newpackage.save() sub_total = sub_total + amount*price #Factura vinculada a la solicitud dist = Distributor.objects.all().first() dist_rif = dist.rif dist_name = dist.dist_name taxes = sub_total*0.12 total = sub_total + taxes banklist = Account.objects.all() totalacc = banklist.count() selectb = int(random.randrange(0,totalacc-1,1)) #print selectb bank = banklist[selectb] account_number = bank.account_number newbill = Bill( dist_rif=dist_rif, dist_name=dist_name, account_number=account_number, sub_total=sub_total, taxes=taxes, total=total, payment_status='00', request=newdelrequest) newbill.save() #Registrar evento mssg = u'El comercio ' + associated_comm.assoc_name + u' ha generado una solicitud de envío en el sistema.' newlogentry = LogEntry( event_type='REQ', event_desc=mssg) newlogentry.save() #Construir respuesta print delivery_date #delivery_date_local = delivery_date.replace(tzinfo=get_current_timezone()) delivery_date_local = delivery_date.astimezone(timezone('America/Caracas')).strftime('%d-%m-%Y %H:%M') print daystodel print delivery_date_local if newstatus.status == '00': stat = 'Recibido' elif newstatus.status == '01': stat = 'Por despachar' elif newstatus.status == '02': stat = 'Despachada' elif newstatus.status == '03': stat = 'Entregada' answer = etree.SubElement(root, 'respuesta') etree.SubElement(answer,'costo').text = str(total) etree.SubElement(answer,'fechaEntrega').text = str(delivery_date_local) etree.SubElement(answer,'tracking').text = str(tracking_number) etree.SubElement(answer,'estado').text = str(stat) #print etree.tostring(root, pretty_print=True) dtdstring = StringIO.StringIO('<!ELEMENT despacho (id,comercio,productos,datosEnvio,respuesta)><!ELEMENT id (#PCDATA)><!ELEMENT comercio (rif,nombre)><!ELEMENT rif (#PCDATA)><!ELEMENT nombre (#PCDATA)><!ELEMENT productos (producto+)><!ELEMENT producto (id,nombre,cantidad,medidas)><!ELEMENT id (#PCDATA)><!ELEMENT nombre (#PCDATA)><!ELEMENT cantidad (#PCDATA)><!ELEMENT medidas (peso,largo,ancho,alto)><!ELEMENT peso (#PCDATA)><!ELEMENT largo (#PCDATA)><!ELEMENT ancho (#PCDATA)><!ELEMENT alto (#PCDATA)><!ELEMENT datosEnvio (nombreDestinatario,telefonos,direccion,zip,ciudad,pais)><!ELEMENT nombreDestinatario (#PCDATA)><!ELEMENT telefonos (telefonoContacto+)><!ELEMENT telefonoContacto (#PCDATA)><!ELEMENT direccion (#PCDATA)><!ELEMENT zip (#PCDATA)><!ELEMENT ciudad (#PCDATA)><!ELEMENT pais (#PCDATA)><!ELEMENT respuesta (costo,fechaEntrega,tracking,estado)><!ELEMENT costo (#PCDATA)><!ELEMENT fechaEntrega (#PCDATA)><!ELEMENT tracking (#PCDATA)><!ELEMENT estado (#PCDATA)>') dtd = etree.DTD(dtdstring) #print dtd.validate(root) #Enviar factura a comercio reqbody = xmlbill(newbill.pk) urlassc = associated_comm.bill_webservice #print urlassc ra = requests.post(urlassc,data=reqbody,headers={'content-type':'application/xml'}) #Enviar factura a banco urlbank = bank.bill_webservice #print urlbank rb = requests.post(urlbank,data=reqbody,headers={'content-type':'application/xml'}) return HttpResponse(etree.tostring(root, pretty_print=True),content_type='application/xml') else: print 'El comercio no se encuentra registrado' return HttpResponse(status=400) else: print 'No pase la validacion contra DTD' return HttpResponse(status=400) else: return HttpResponse(status=400) else: return HttpResponse(status=400)
def jquery_time_convert(dt) : TZ = timezone(settings.TIME_ZONE) return TZ.localize(dt.replace(microsecond=0)).astimezone(utc).replace(tzinfo=None).isoformat() + 'Z'
def publish(self): self.published_date = timezone() self.save()
def __call__(self, request): tz = timezone('US/Pacific') django.utils.timezone.activate(tz) return self.get_response(request)
def save_admin(request): """ View is called when add_entry is submitted and passes the data off here in order to save it to the database. It returns the viewer back to the index template, in order to see the results of the database addition at the top of the administration records. :param request: :return: """ if request.method == "POST": add_administration_form = UsageForm({ 'sub': request.POST['sub'], 'dosage': request.POST['dosage'], 'timestamp': request.POST['timestamp'], 'notes': request.POST['notes'] }) # localize the timestamp central_tz = timezone(Const.Time_Zone) timestamp = central_tz.localize( datetime.strptime(request.POST['timestamp'], '%Y-%m-%d %H:%M:%S')) print(str(timestamp)) new_administration = Usage( sub=Substance.objects.get(id=request.POST['sub']), user=request.user, dosage=request.POST['dosage'], timestamp=timestamp, notes=request.POST['notes']) try: new_administration.save() except Exception as e: error_message = "Unable to save to db: " + str( e) + "admin: " + str(new_administration) context = { 'add_admin_form': add_administration_form, 'error_message': error_message, } return render(request, 'recadm/add_entry.html', MiscMethods.add_header_info(context)) # code for the successful save of the record and return to the index # follows here mydata = [] recent_administrations = Usage.objects.filter( user=request.user).order_by('-timestamp') paginator = Paginator(recent_administrations, 15) # 15 admins per page page = request.GET.get('page') administrations = paginator.get_page(page) for administration in administrations: # localization needed? if MiscMethods.is_localization_needed(administration.timestamp): tmp_dt = MiscMethods.localize_timestamp(administration.timestamp) else: tmp_dt = administration.timestamp mydata.append({ 'ts': tmp_dt, 'id': administration.id, 'dosage': administration.dosage, 'substance_name': administration.sub, }) context = { 'mydata': mydata, 'administrations': administrations, } return render(request, 'recadm/index.html', MiscMethods.add_header_info(context))
def create(self, validated_data): self.date_time = timezone(self.date_time).make_aware() return UserLocationData.objects.create(**validated_data)
def cme_export_csv(request, course_id, datatype): import csv from django.utils.encoding import smart_str from opaque_keys.edx.locations import SlashSeparatedCourseKey cid = CourseKey.from_string(course_id) response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = "attachment; filename=users.csv" writer = csv.writer(response, csv.excel) response.write(u"\ufeff".encode( "utf8")) # BOM (optional...Excel needs it to open UTF-8 file properly) course_id = str(cid) course_number = course_id.split("+") user = request.user course_details = CourseOverview.objects.get(id=cid) course_exinfo = course_extrainfo.objects.get(course_id=cid) webinar_time = int(course_exinfo.total_webinar_hours) if user.is_staff: if datatype == "enrolled": writer.writerow([ smart_str(u"Userid"), smart_str(u"Firstname"), smart_str(u"Last Name"), smart_str(u"Emailid"), smart_str(u"ISD"), smart_str(u"Mobile number"), smart_str(u"Country"), smart_str(u"City"), smart_str(u"Place of work"), smart_str(u"Profession"), smart_str(u"Enrolled date"), ]) response["Content-Disposition"] = ("attachment; filename=" + str(course_number[1]) + "_enrolledusers.csv") crows = CourseEnrollment.objects.filter(course_id=cid) for row in crows: logs.info("id--> %s", row.user_id) try: assoc_user = User.objects.get(id=row.user_id) user_detail = getuserfullprofile(row.user_id) user_ext = userdetails(assoc_user.id) if (user_ext.user_extra_data != "" and "{" in user_ext.user_extra_data): extd = ast.literal_eval(user_ext.user_extra_data) else: extd = {} ext = json.dumps(extd) ext = eval(ext) name = user_detail.name.split(" ") fname = name[0] if len(name) > 1: lname = name[1] else: lname = "NA" if ext.get("isdcode"): isdcode = ext["isdcode"] elif ext.get("country_code"): isdcode = ext.get("country_code") else: isdcode = "NA" if ext.get("placeofwork"): placeofwork = ext["placeofwork"] elif ext.get("place_of_work"): placeofwork = ext.get("place_of_work") else: placeofwork = "NA" profession = ext.get("profession") if profession: profession = ext["profession"] else: profession = "NA" writer.writerow([ smart_str(row.user_id), smart_str(fname), smart_str(lname), smart_str(assoc_user.email), smart_str(isdcode), smart_str(user_ext.phone), smart_str(user_ext.rcountry), smart_str(user_ext.rcity), smart_str(placeofwork), smart_str(profession), smart_str(row.created) ]) except ObjectDoesNotExist: usernotfound = 0 elif datatype == "viewers": writer.writerow([ smart_str(u"Userid"), smart_str(u"Firstname"), smart_str(u"Last Name"), smart_str(u"Emailid"), smart_str(u"ISD"), smart_str(u"Mobile number"), smart_str(u"Country"), smart_str(u"City"), smart_str(u"Place of work"), smart_str(u"Profession"), smart_str(u"Start date"), smart_str(u"Start time"), smart_str(u"End date"), smart_str(u"End time"), smart_str(u"Duration"), ]) response["Content-Disposition"] = ("attachment; filename=" + str(course_number[1]) + "_viewers.csv") # vrows = ( # StudentModule.objects.filter( # course_id=cid, module_type="course" # ) # .values("student_id", "created", "state") # .annotate(dcount=Count("student_id")) # ) # vrows = StudentModule.objects.filter(course_id=cid,module_type='sequential').values('student_id','created','state').distinct() vrows = (user_session_tracking.objects.filter( course_id=cid, pagein__gte=course_details.start).values( "user_id", "course_id").distinct()[300:450]) count = 0 for vrow in vrows: count = count + 1 logs.info("id--> %s,%s", vrow["user_id"], count) userlogin = user_session_tracking.objects.filter( course_id=vrow["course_id"], user_id=vrow["user_id"], pagein__gte=course_details.start).first() userlogout = user_session_tracking.objects.filter( course_id=vrow["course_id"], user_id=vrow["user_id"]).last() assoc_user = User.objects.get(id=vrow["user_id"]) user_ext = userdetails(assoc_user.id) intime = userlogin.pagein.astimezone(timezone("Asia/Kolkata")) if userlogout.track_updated == 0: new_out_time = userlogout.pageout + datetime.timedelta( hours=webinar_time) outime = new_out_time.astimezone(timezone("Asia/Kolkata")) total_time = str(new_out_time - userlogin.pagein) else: outime = userlogout.pageout.astimezone( timezone("Asia/Kolkata")) total_time = str(userlogout.pageout - userlogin.pagein) user_detail = getuserfullprofile(assoc_user.id) extd = ast.literal_eval(user_ext.user_extra_data) ext = json.dumps(extd) ext = eval(ext) if (user_ext.user_extra_data != "" and "{" in user_ext.user_extra_data): extd = ast.literal_eval(user_ext.user_extra_data) else: extd = {} ext = json.dumps(extd) ext = eval(ext) name = user_detail.name.split(" ") fname = name[0] if len(name) > 1: lname = name[1] else: lname = "NA" if ext.get("isdcode"): isdcode = ext["isdcode"] elif ext.get("country_code"): isdcode = ext.get("country_code") else: isdcode = "NA" if ext.get("placeofwork"): placeofwork = ext["placeofwork"] elif ext.get("place_of_work"): placeofwork = ext.get("place_of_work") else: placeofwork = "NA" profession = ext.get("profession") if profession: profession = ext["profession"] else: profession = "NA" writer.writerow([ smart_str(vrow["user_id"]), smart_str(fname), smart_str(lname), smart_str(assoc_user.email), smart_str(isdcode), smart_str(user_ext.phone), smart_str(user_ext.rcountry), smart_str(user_ext.rcity), smart_str(placeofwork), smart_str(profession), smart_str(intime.strftime("%b %d, %Y ")), smart_str(intime.strftime("%H:%M")), smart_str(outime.strftime("%b %d, %Y ")), smart_str(outime.strftime("%H:%M")), smart_str(total_time), ]) return response
from django.core.urlresolvers import reverse from django.db import models from django.utils import timezone # Create your models here. from pytz import timezone from datetime import datetime buenos_aires = timezone('America/Argentina/Buenos_Aires') class Expense(models.Model): fecha = models.DateField(default=datetime.now(buenos_aires).replace( tzinfo=None)) descripcion = models.CharField(max_length=100) precio = models.FloatField() extraordinario = models.IntegerField(choices=((1, ("Si")), (0, ("No"))), default=0) class Meta: ordering = ['-id'] def get_absolute_url(self): return reverse('expense-detail', kwargs={'pk': self.pk})
def create_question(question_text, days): time = timezone() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time)
def created_at_korean_time(self): korean_timezone = timezone(settings.TIME_ZONE) return self.created_at.astimezone(korean_timezone)
from django.core.management.base import BaseCommand from django.utils import timezone from datetime import datetime from pytz import timezone from tzlocal import get_localzone now_utc = datetime.now(timezone('UTC')) now_local = now_utc.astimezone(get_localzone()) class Command(BaseCommand): help = 'Displays current time' def handle(self, *args, **kwargs): time = now_local.strftime('%X') self.stdout.write(self.style.SUCCESS("\nIt's now %s\n" % time))
def TopBet_NCAAF(request): url = 'http://topbet.eu/sportsbook/college-football/ncaa' update_counter = 0 newmatch_counter = 0 r = requests.get(url) soup = BeautifulSoup(r.text) soup.find_all('td') events = soup.findAll("div",{"class":"event"}) #single event for single in events: header = single.find_all('h3') tds = single.find_all('td') matchuparray = [] for td in tds: line = td.get_text() line = line.strip() matchuparray.append(line) headerarray =[] for x in header: line = x.get_text() line = line.strip() headerarray.append(line) headerstring = headerarray.pop() headersplit = headerstring.split('\n') if 'O' in headersplit: headersplit.remove('O') if '' in headersplit: headersplit.remove('') header_date = headersplit[0] header_time = headersplit[1] match = re.search(r'\d{4}-\d{2}-\d{2}', header_date) matchup_summary = header_date.replace(match.group(),'').strip() away_full_name = matchup_summary[0:matchup_summary.find(' at ')].strip() home_full_name = matchup_summary[matchup_summary.find( ' at ')+4:len(matchup_summary)].strip() matchupdatetime_string = match.group() +' '+header_time matchupdatetime = datetime.datetime.strptime(matchupdatetime_string, '%Y-%m-%d %H:%M') eastern = timezone('US/Eastern') matchupdatetime = eastern.localize(matchupdatetime) matchupdatetime = matchupdatetime - timedelta(hours = 4) matchuparray.reverse() away_rotid_temp= matchuparray.pop() away_rotid_temp = away_rotid_temp.strip() away_rotid_temp = away_rotid_temp.split('\n') away_rotid_temp.remove('') away_rotid = away_rotid_temp[1].strip() away_team_str= matchuparray.pop() away_spread=matchuparray.pop() away_spread_line=matchuparray.pop() #temp = matchuparray.pop() spread_on_string = matchuparray.pop() away_money_line=matchuparray.pop() #matchuparray.pop() moneyline_on_string = matchuparray.pop() #matchuparray.pop() over_string=matchuparray.pop() away_over = matchuparray.pop() over_line = matchuparray.pop() #matchuparray.pop() overunder_on_string = matchuparray.pop() home_rotid= matchuparray.pop() home_team_str = matchuparray.pop() home_spread = matchuparray.pop() home_spread_line=matchuparray.pop() bet_str3_spread = matchuparray.pop() home_money_line= matchuparray.pop() betstr5_moneyline_on_string = matchuparray.pop() Under_str = matchuparray.pop() over_under_repeat = matchuparray.pop() under_line = matchuparray.pop() bet_str4_overunder = matchuparray.pop() moneyline_on = True overunder_on = True spread_on = True city_id_away = away_team_str[0:3] city_id_home = home_team_str[0:3] if moneyline_on_string == 'Off': moneyline_on = False if spread_on_string == 'Off': spread_on = False if overunder_on_string == 'Off': overunder_on = False away_mascot = away_full_name.replace(away_team_str,'').strip() home_mascot = home_full_name.replace(home_team_str,'').strip() away_team = Team.objects.filter(league = "NCAAF", city = away_team_str, full_name = away_full_name) home_team = Team.objects.filter(league = "NCAAF", city = home_team_str, full_name = home_full_name) if away_team.count() == 0: away_team = Team(league = "NCAAF", city = away_team_str, team_name = away_mascot, full_name = away_full_name) away_team.save() else: away_team = away_team[0] away_team.city_id = city_id_away away_team.save() if home_team.count() == 0: home_team = Team(league = "NCAAF", city = home_team_str, team_name = home_mascot, full_name = home_full_name) home_team.save() else: home_team = home_team[0] home_team.city_id = city_id_home home_team.save() result_exists = Matchup.objects.filter(away_rotid=away_rotid, away_team = away_team, home_team = home_team, league = "NCAAF").count() if result_exists > 0: newmatchup = Matchup.objects.get(away_rotid=away_rotid, league="NCAAF", away_team = away_team, home_team = home_team) newmatchup.date = matchupdatetime newmatchup.away_rotid = away_rotid newmatchup.away_team = away_team newmatchup.away_spread = away_spread newmatchup.away_spread_line = away_spread_line newmatchup.away_money_line = away_money_line newmatchup.over_under = away_over newmatchup.over_line = over_line newmatchup.under_line = under_line newmatchup.home_rotid= home_rotid newmatchup.home_team = home_team newmatchup.home_spread =home_spread newmatchup.home_spread_line = home_spread_line newmatchup.home_money_line = home_money_line newmatchup.moneyline_on = moneyline_on newmatchup.overunder_on = overunder_on newmatchup.spread_on = spread_on newmatchup.save() logger.debug("%s @ %s matchup UPDATED in NCAAF" % (newmatchup.home_team.city, newmatchup.away_team.city)) update_counter = update_counter + 1 else: newmatchup = Matchup( date = matchupdatetime, league = "NCAAF", away_rotid = away_rotid, away_team = away_team, away_spread = away_spread, away_spread_line = away_spread_line, away_money_line = away_money_line, over_under = away_over, over_line = over_line, under_line = under_line, home_rotid= home_rotid, home_team = home_team, home_spread =home_spread, home_spread_line = home_spread_line, moneyline_on = moneyline_on, overunder_on = overunder_on, spread_on = spread_on, home_money_line = home_money_line) newmatchup.save() newmatch_counter = newmatch_counter +1 logger.debug("%s @ %s matchup ADDED to NCAAF" % (newmatchup.home_team.city, newmatchup.away_team.city)) logger.info("%d NCAAF Matchups added. %d NCAAF Matchups Updated" % (newmatch_counter, update_counter)) return render(request, 'bets/admin_functions.html')