def generateId(self): last_id = self.getLastId() # check if year is current if date.today().strftime("%y") == last_id[0:2]: job_id = eval(last_id) + 1 else: job_id = eval(date.today().strftime("%y")) + ('001')
def index(request): current_date = date.today() for i in range(len(todos)): ddate = todos[i].due_date if current_date.year >= ddate.year and current_date.month >= ddate.month and current_date.day > ddate.day: todos[i].archive = True todos[i].save() if request.method == "POST": if "taskAdd" in request.POST: title = request.POST["description"] #title due_date = request.POST["date"] #date label = request.POST["label_select"] #category status = request.POST["status_select"] # print("Start",list(map(int, due_date.split("-"))),"end") Todo = TodoList(title=title, due_date=due_date, label=label, status=status) Todo.save() #saving the todo # print("task saved") return redirect("/") #reloading the page return render(request, "pages/indexN.html", { "todos": todos, 'labelv': label_json, 'statusv': status_json })
def investment_invest(request, pk): plan = growthInvestment.objects.get(id=pk) user = request.user.monetaryuser plan_amount = plan.current_amount amount = 10 if request.method == 'POST': amount = request.POST.get('value') record = monetaryRecord.objects.create( user=user, naming="Invested in " + plan.naming, category='Investment', amount=amount, date=date.today() ) record.save() plan.current_amount = plan_amount + Decimal(amount) plan.save() return redirect('/investments/investments/') context = {'amount': amount, 'plan': plan} context = {**context_add(request), **context} return render(request, '/investment_invest.html', context)
def index(request): now = datetime.now() today = date.today() date1 = now - timedelta(days=1) date3 = now + timedelta(days=1) date4 = now + timedelta(days=2) date5 = now + timedelta(days=3) date6 = now + timedelta(days=4) rec1 = Record.objects.filter(date_appointed__date=date1) rec2 = Record.objects.filter(date_appointed__date=now) rec3 = Record.objects.filter(date_appointed__date=date3) rec4 = Record.objects.filter(date_appointed__date=date4) rec5 = Record.objects.filter(date_appointed__date=date5) rec6 = Record.objects.filter(date_appointed__date=date6) context = { 'rec1': rec1, 'rec2': rec2, 'rec3': rec3, 'rec4': rec4, 'rec5': rec5, 'rec6': rec6, 'now': now, 'date1': date1, 'date3': date3, 'date4': date4, 'date5': date5, 'date6': date6, } return render(request, 'log/index.html', context)
def GetSWexponent(ExponentID=None,BeginTime=None,EndTime=None): if(ExponentID==None): print("沒有传入申万之一指数代码,数据将返回所有申万一级指数的数据") ExponentID = '801010.SI,801020.SI,801030.SI,\ 801040.SI,801050.SI,801080.SI,801110.SI,\ 801120.SI,801130.SI,801140.SI,801150.SI,\ 801160.SI,801170.SI,801180.SI,801200.SI,\ 801210.SI,801230.SI,801710.SI,801720.SI,\ 801730.SI,801740.SI,801750.SI,801760.SI,\ 801770.SI,801780.SI,801790.SI,801880.SI,\ 801890.SI' if(BeginTime==None): BeginTime = '2010-01-01' if(EndTime==None): EndTime=date.today(); tmp = (ExponentID,'close',BeginTime,EndTime,'Fill=Previous') data = w.wsd(*tmp) Value = [] for i in range(0,len(data.Codes)): for j in range(0,len(data.Data[0])): value = data.Data[i][j]; if isnan(value): value=0.0 Value.append((str(data.Codes[i]),data.Times[j].strftime("%Y-%m-%d"),str(value))) for n in Value: print(n) return Value
def investment_cash_out(request, pk): plan = growthInvestment.objects.get(id=pk) user = request.user.monetaryuser plan_amount = plan.current_amount value = 10 if request.method == 'POST': value = request.POST.get('cash-value') plan.current_amount = plan_amount - Decimal(value) plan.save() record = monetaryRecord.objects.create( user=user, naming='Investment Cash', category='Investment Cash', amount=value, date=date.today() ) record.save() return redirect('/investments/') context = {'plan': plan, 'value': value} context = {**context_add(request), **context} return render(request, 'investments/investment_cash-out.html', context)
def getDowAlbumName(albumLink): albumReader = urlopen(albumLink); albumSoup = BeautifulSoup(albumReader, "html.parser"); albumNameElm = albumSoup.find("span", { "class" : "red" }); if (albumNameElm != None) : return "{} [{}]".format(albumNameElm.string.strip(), str(date.today().year)); return None
def investment_invest_all(request): plans = request.user.monetaryuser.growthinvestment_set.all() plan_all = Decimal(plans.count()) user = request.user.monetaryuser tip = 10 if request.method == 'POST': tip = request.POST.get('tip-value') record = monetaryRecord.objects.create( user=user, naming="Invested in all plans", category='Investment', amount=tip, date=date.today() ) record.save() tip_ration = (Decimal(tip) / plan_all) for plan in plans: plan_amount = plan.current_amount plan.current_amount = plan_amount + tip_ration plan.save() return redirect('/investments/') context = {'tip': tip, 'plans': plans, 'plan_all': plan_all} context = {**context_add(request), **context} return render(request, 'investments/investment_invest_all.html', context)
def tip_all_savings(request): jars = request.user.monetaryuser.savingsjar_set.all() jar_all = Decimal(jars.count()) user = request.user.monetaryuser tip = 10 if request.method == 'POST': tip = request.POST.get('tip-value') record = monetaryRecord.objects.create( user=user, naming="Tipped all Savings", category='Saving tipped', amount=tip, date=date.today() ) record.save() tip_ration = (Decimal(tip) / jar_all) for jar in jars: jar_amount = jar.amount jar.amount = jar_amount + tip_ration jar.save() return redirect('/savings/') context = {'tip': tip, 'jars': jars, 'jar_all': jar_all} context = {**context_add(request), **context} return render(request, 'savings/savings_tip_all.html', context)
def validate_date_naklad(value): if value > date.today(): raise ValidationError( 'Нельзя указать дату накладной больше сегодняшней') elif value < date(1970, 1, 1): raise ValidationError( 'Дата накладной должна быть старше 1 января 1970')
def findAllPractice(status): myconn=getConnection() cur = myconn.cursor() sql = "select word.* from word,review where word.id=review.id_Word and status=%s and date_practice=%s " par =(status,date.today()) cur.execute(sql,par) myresult = cur.fetchall() return myresult
def add_to_order(self, book_id): now = date.today() connect = sqlite3.connect(self.Database) cursor = connect.cursor() cursor.execute( "INSERT INTO _ORDER (START_DATE, BOOK_ID, USER_ID) VALUES (\"{}\", {}, {}); " .format(now, book_id, self.id)) connect.commit()
def get_first_dateofthemonth(): today = date.today() first_day = today.replace(day=1) # if today.day > 25: # first_day = (first_day + relativedelta(months=1)) # else: # first_day = first_day return first_day
def get_from_to_dates(i_from_date, i_to_date): try: if i_from_date is None: from_date = str(date.today() + timedelta(days=-30)) else: from_date = i_from_date from_date = datetime.strptime(from_date, '%Y-%m-%d').strftime('%Y%m%d') if i_to_date is None: to_date = str(date.today() + timedelta(days=-1)) else: to_date = i_to_date to_date = datetime.strptime(to_date, '%Y-%m-%d').strftime('%Y%m%d') return from_date, to_date except ValueError as e: print(e) sys.exit(13)
def get_users(self, period_by_days): headers = self.get_headers() params = { 'id': self.counter_id, 'metrics': 'ym:s:users', 'date1': '{}'.format(date.today() - timedelta(days=period_by_days)) } r = requests.get(self.API_STAT_URL + 'data', params, headers=headers) return r.json()['data'][0]['metrics'][0]
def update(self, validated_data, pk): user = CustomUser.objects.get(pk=pk) user.username = validated_data['username'] user.email = validated_data['email'] user.password = validated_data['password'] user.bio = validated_data['bio'] user.profile_pic = validated_data['profile_pic'] user.updated_at = date.today() return user
class Utilities(models.Model): fechaApertura = None today = date.today() todayDateTimeNow = getTodayDateTime() def getTodayDateTimeNow(self): return getTodayDateTime() def getTodayDateTimeNowDBFormat(self): return getTodayDateTimeNowDBFormat()
def voto(ano): from _datetime import date atual = date.today().year idade = atual - ano if idade < 16: return f'Com {idade} anos: NÃO VOTA.' elif 16 <= idade <= 18 or idade > 65: return f'Com {idade} anos: VOTO OPCIONAL.' else: return f'Com {idade} anos: VOTO OBRIGATÓRIO.'
def album_preorder(request): albums = Album.objects.all() alb = [] for a in albums: fecha = a.fecha hoy = date.today() result = diferencia(fecha, hoy) if result < 0: alb.append(a) return render(request, 'album_preorder.html', {'alb': alb})
def RegressionTwo(): daily1 = '/Volumes/Data/StockAssistant/EasyStock/TreaderAnalysis/data/output/每日数据/2019-08-20.xlsx' daily2 = '/Volumes/Data/StockAssistant/EasyStock/TreaderAnalysis/data/output/每日数据/2019-08-26.xlsx' srcFile = '/Volumes/Data/StockAssistant/EasyStock/TreaderAnalysis/data/output/多日过滤Ex/2019-08-20/BOLL带宽_2019-08-20.xlsx' destFile = '/Volumes/Data/StockAssistant/EasyStock/TreaderAnalysis/data/output/BOLL带宽_2019-08-20.xlsx' tmp = "/tmp/tmp_%s.xlsx" % (date.today()) RegressionTest(daily1, srcFile, tmp) RegressionTest(daily2, tmp, destFile)
def get_queryset(self): if self.request.method == 'GET': start_date = self.request.GET.get('start_date') end_date = self.request.GET.get('end_date') if (start_date == None or end_date == None): return Emi.objects.filter(amt__exact=0, due_date__lt=date.today()) return Emi.objects.filter(due_date__gt=start_date, due_date__lt=end_date, amt__exact=0)
def testone(): xx = "guru4434,education is fun" r1 = re.findall(r"^\d.+", xx) print(r1) today = date.today() today2 = today.month today3 = today.year print(today) print(today2) print(today3)
def todolist(request, interval='all'): assert isinstance(request, HttpRequest) if request.method == 'GET' and 'search' in request.GET: search = request.GET['search'] if not search: tasks = {} else: tasks = Task.objects.filter(Q(name__icontains=search) | Q(description__icontains=search) | Q(date__icontains=search)) return render(request, 'app/todolist.html', { 'title': 'ToDoList', 'year':datetime.now().year, 'message': "Hello", 'tasks': tasks, }) now = date.today() step = request.GET.get('step', timedelta(days=1)) tasks = False gap = now if interval == 'today': gap = now elif interval == 'tomorrow': now += timedelta(days=1) gap = now elif interval == 'week': gap = now + timedelta(days=7) elif interval == 'month': gap = now + timedelta(days=31) elif interval == 'year': gap = now + timedelta(days=365) else: tasks = Task.objects.all() if not tasks: currentDay = str(now.year) + '-' + str(now.month) + '-' + str(now.day) nextDay = str(gap.year) + '-' + str(gap.month) + '-' + str(gap.day) tasks = Task.objects.filter(date__range=[currentDay, nextDay]) return render( request, 'app/todolist.html', { 'title': 'ToDoList', 'year':datetime.now().year, 'message': "Hello", 'tasks': tasks, } )
def updateStatus(id,status): myconn=getConnection() cur = myconn.cursor() sql="update review set status = %s where id_Word = %s and date_practice= %s" par =(status,id,date.today()) try: cur.execute(sql,par) myconn.commit() return 1 except: return 0
def create_test_description(self): """ Create a descripton list element with information about the test case. """ dl = Element("dl") TestCase.create_dl_dt(dl, "Project:", self.project) TestCase.create_dl_dt(dl, "Author:", self.author) adate = str(date.today()) TestCase.create_dl_dt(dl, "Date:", adate) TestCase.create_dl_dt(dl, "Repeatable:", "Yes") TestCase.create_dl_dt(dl, "Description:", self.description) return dl
def setDates(): currentDate = date.today() ui.EstStartDay_date.setDate(currentDate) ui.DepositDate_date.setDate(currentDate) ui.StartDate_date.setDate(currentDate) ui.PlanCheckReturn_date.setDate(currentDate) ui.EngDeadline_date.setDate(currentDate) ui.DftDeadline_date.setDate(currentDate) ui.PlanCheck_date.setDate(currentDate) ui.EngRevision_date.setDate(currentDate) ui.DftRevision_date.setDate(currentDate) ui.FinalDeadline_date.setDate(currentDate)
def todolist(request, interval='all'): assert isinstance(request, HttpRequest) if request.method == 'GET' and 'search' in request.GET: search = request.GET['search'] if not search: tasks = {} else: tasks = Task.objects.filter( Q(name__icontains=search) | Q(description__icontains=search) | Q(date__icontains=search)) return render( request, 'app/todolist.html', { 'title': 'ToDoList', 'year': datetime.now().year, 'message': "Hello", 'tasks': tasks, }) now = date.today() step = request.GET.get('step', timedelta(days=1)) tasks = False gap = now if interval == 'today': gap = now elif interval == 'tomorrow': now += timedelta(days=1) gap = now elif interval == 'week': gap = now + timedelta(days=7) elif interval == 'month': gap = now + timedelta(days=31) elif interval == 'year': gap = now + timedelta(days=365) else: tasks = Task.objects.all() if not tasks: currentDay = str(now.year) + '-' + str(now.month) + '-' + str(now.day) nextDay = str(gap.year) + '-' + str(gap.month) + '-' + str(gap.day) tasks = Task.objects.filter(date__range=[currentDay, nextDay]) return render( request, 'app/todolist.html', { 'title': 'ToDoList', 'year': datetime.now().year, 'message': "Hello", 'tasks': tasks, })
def arriveContainers(port, driver): driver.find_element_by_id("clayView:ns_7_40O00G3VMR0D00A4BG79CQ00A5_00000:_idsc00001:portId").clear() driver.find_element_by_id("clayView:ns_7_40O00G3VMR0D00A4BG79CQ00A5_00000:_idsc00001:portId").send_keys(port) driver.find_element_by_id("clayView:ns_7_40O00G3VMR0D00A4BG79CQ00A5_00000:_idsc00001:_idsc00020").click() todaysDate = date.today() thisMonth = str(todaysDate.month) if len(thisMonth)==1: thisMonth ="0"+thisMonth thisDay = str(todaysDate.day) if len(thisDay)==1: thisDay ="0"+thisDay todaysDate=thisMonth+"/"+thisDay+"/"+str(todaysDate.year) done = False j=2 driver.implicitly_wait(0) try: driver.find_element_by_css_selector("span[title='Page 1']").click() except: pass driver.implicitly_wait(60) while not done: cells = driver.find_elements_by_css_selector("table[class='datat']>tbody>tr>td") i=0 while i<min(1300, len(cells)): driver.execute_script("arguments[0].scrollIntoView();", cells[i]) if not todaysDate in cells[i+10].text: cells[i].find_element_by_tag_name("input").click() cells[i+1].find_element_by_tag_name("input").send_keys(todaysDate) cells[i+2].find_element_by_tag_name("input").send_keys("08:00") cells[i+3].find_element_by_tag_name("input").send_keys(port) i+=13 else: break driver.implicitly_wait(0) try: driver.find_element_by_css_selector("span[title='Page " +str(j)+ "']").click() j+=1 except: done=True driver.implicitly_wait(60) driver.find_element_by_id("clayView:ns_7_40O00G3VMR0D00A4BG79CQ00A5_00000:_idsc00001:_idsc00078").click() if j>2: sleepTime =(j-1)*30 else: sleepTime= ceil(i/52) sleep(sleepTime)
def send_conflict_notification(request, persons: QuerySet): connection = mail.get_connection() today = date.today() last_year = date(year=today.year - 1, month=12, day=31) # Manually open the connection connection.open() messages = [] for p in persons: if not p.eligibile_onlyOneClub(): club_memberships: List[ PersonToClubMembership] = p.get_current_clubmemberships() for m in club_memberships: club_admins = User.objects.filter( groups__name=f"club_admin_{m.club.name}") club_memberships: List[ PersonToClubMembership] = p.get_current_clubmemberships() templates = (loader.get_template( "mails/nationals_conflict/send_conflict_notification_club_admin.j2" ), ) context = { "person": p, "club_memberships": club_memberships, "affected_club_membership": m, "last_year": last_year, "request": request, } for admin in club_admins: context["recepient"] = admin msg = mail.EmailMessage( subject= f"Konflikt bei der Vereinsmeldung von {p.firstname} {p.lastname}", body=templates[0].render(context), to=[admin.email], from_email="*****@*****.**", connection=connection, ) msg.content_subtype = "html" messages.append(msg) # Send the two emails in a single call - connection.send_messages(messages) # The connection was already open so send_messages() doesn't close it. # We need to manually close the connection. connection.close()
def get_from_to_dates(i_from_date, i_to_date): """ :param str 'YYYY-MM-DD' i_from_date: pull data from this date [includes] :param str 'YYYY-MM-DD' i_to_date: pull data till this date [includes] :exception ValueError: date format is not as asked :return tuple: dates in format 'YYYYMMDD' - dates ready to be scrapped """ try: if i_from_date is None: from_date = str(date.today() + timedelta(days=-30)) else: from_date = i_from_date from_date = datetime.strptime(from_date, '%Y-%m-%d').strftime('%Y%m%d') if i_to_date is None: to_date = str(date.today() + timedelta(days=-1)) else: to_date = i_to_date to_date = datetime.strptime(to_date, '%Y-%m-%d').strftime('%Y%m%d') return from_date, to_date except ValueError as e: print(e) sys.exit(13)
def break_saving(request, pk): jar = savingsJar.objects.get(id=pk) user = request.user.monetaryuser if request.method == 'POST': record = monetaryRecord.objects.create( user=user, naming="Funds from " + jar.naming, category='Saving Funds', amount=jar.amount, date=date.today() ) record.save() jar.delete() return redirect('/savings/') context = {'jar': jar} context = {**context_add(request), **context} return render(request, 'savings/savings_break.html', context)
def ExponentScale(fundid=None, begintime='2010-01-01', endtime=date.today()): if(fundid == None): fundid = FundID() param = (fundid, 'prt_totalasset', begintime, endtime, 'Period=Q', 'Fill=Previous') data = w.wsd(*param) Value = [] for i in range(0, len(data.Codes)): for j in range(0, len(data.Data[0])): stockvalue = data.Data[i][j] print(stockvalue) if(stockvalue is None or isnan(stockvalue)): stockvalue = 0.0 record = (data.Codes[i], data.Times[j].strftime("%Y-%m-%d"), stockvalue) print(record) Value.append(record) return Value
def load_checks(self): """ Cargamos cheques mayores a la fecha actual y menores a la fecha de recepción """ today = date.today().strftime('%Y-%m-%d') check_list = self.env['eliterp.checks'].search([ ('date', '<=', today), ('check_date', '>=', today), ('type', '=', 'receipts'), ('state', '=', 'received') ]) lines = [] for check in check_list: lines.append([ 0, 0, { 'check_id': check.id, 'check_number': check.name, 'account_id': check.account_id.id, 'bank_id': check.bank_id.id, 'amount': check.amount, 'date_due': check.check_date } ]) return self.update({'lines_deposits_checks': lines})
def call_high_charts(): error = 'error' keyword = request.args.get('keyword') today = date.today() startDate = today + relativedelta(months=-6) url = ('https://api.tiingo.com/iex/' + keyword +'/prices?startDate=' + str(startDate) + '&resampleFreq=12hour&columns=open,high,low,close,volume&token=' + tiingo_api_key) output_json = defaultdict(dict) response = requests.get(url) response_json = response.json() if(response.status_code==200): if response_json: for i, ant in enumerate(response_json): output_json[i]['date'] = ant['date'][:10] output_json[i]['close'] = ant['close'] output_json[i]['volume'] = ant['volume'] return jsonify(output_json) else: return 0 else: return jsonify(error)
def validate_date_naklad(value): if value > date.today(): raise ValidationError('Нельзя указать дату накладной больше сегодняшней') elif value < date(1970, 1, 1): raise ValidationError('Дата накладной должна быть старше 1 января 1970')
def activate(self, date_str, date_bool = False): if date_bool != False: self.date = datetime.strptime(date_str, '%m/%d/%Y') else: self.date = date.today() self.job_id = self.generateId(date_str)
def IndustryConfiguration(fundid=None, industry=None, begintime='2010-01-01', endtime=date.today()): if(fundid == None): print("没选择基金,默认为全部基金") fundid = FundID() if(industry == None): print("未选择行业,默认为全部19个新证监会行业指标") industry = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,15,16, 17, 18, 19] Value = [] for k in range(0, len(industry)): param = (fundid, 'prt_stockvalue_industrytoasset2', begintime, endtime, 'industry=' + str(industry[k]), 'Period=Q', 'Fill=Previous') data = w.wsd(*param) if(data.ErrorCode != 0): print("Wind Error") for i in range(0, len(data.Codes)): for j in range(0, len(data.Data[0])): value = data.Data[i][j] if(value is None or isnan(value)): value = 0.0 record = (data.Codes[i], data.Times[j].strftime("%Y-%m-%d"), industry[k], value) Value.append(record) return Value
def validate_warranty_date(value): if value <= date.today(): raise ValidationError('Дата гарантии должна быть больше сегодняшней даты.')