def get_date_completed_product_range(self, start_date, end_date=None): """Get all the products completed by the worker between these dates.""" if end_date is None: end_date = start_date + timedelta(months=1) - timedelta(days=1) # TODO: figure out something without having to import kit and products ret = self.products_completed.filter( kit__date_received__gte=start_date, kit__date_received__lte=end_date) return ret
def get_date_completed_range(self, start_date, end_date=None): if isinstance(start_date, str) or isinstance(end_date, str): raise TypeError( 'start_date and end_date should be of type datetime.date object' ) if end_date is None: end_date = start_date + timedelta(months=1) - timedelta(days=1) return self.filter(date_completed__lte=end_date, date_completed__gte=start_date)
def begin_date(pre_days, date_str=None, split='-', fix=True): """ return the date string object as date_str - pre_days eg: pre_days = 2 date_str = '2017-02-14' result = '2017-02-12' pre_days = 365 date_str = '2016-01-01' result = '2015-01-01' if pre_days is negative,then we ad days: eg: pre_days = -365 date_str = '2016-01-01' result = '2016-12-31' :param pre_days: pre_days, int :param date_str: date_str, default: current_str_date() :param split: :param fix: whether to fix the date format,eg. 2016-1-1 fix 2016-01-01 :return: date str object """ if date_str is None: date_str = current_str_date() fix = False dt_time = str_to_datetime_fast(date_str, split=split, fix=fix) return str(dt_time + timedelta(days=-pre_days))[:10]
def begin_date(pre_days, date_str=None, split='-', fix=True): """ 返回date_str日期前pre_days天的日期str对象 eg: pre_days = 2 date_str = '2017-02-14' result = '2017-02-12' pre_days = 365 date_str = '2016-01-01' result = '2015-01-01' 如果pre_days是负数,则时间向前推: eg: pre_days = -365 date_str = '2016-01-01' result = '2016-12-31' :param pre_days: pre_days天, int :param date_str: date_str, 默认current_str_date() :param split: :param fix: 是否修复日期不规范的写法,eg. 2016-1-1 fix 2016-01-01 :return: str日期时间对象 """ if date_str is None: date_str = current_str_date() # 如果取current_str_date就没有必要fix了 fix = False dt_time = str_to_datetime_fast(date_str, split=split, fix=fix) return str(dt_time + timedelta(days=-pre_days))[:10]
def get_initial(self): initial = super().get_initial() wpk = self.request.GET.get('worker_pk', None) if wpk: w = Worker.objects.get(pk=wpk) initial['worker'] = w df = None if w.salaries.exists(): df = w.salaries.order_by('-date_to').first().date_to + timedelta(days=1) else: df = w.date_joined dt = df + timedelta(months=1) dt = date(dt.year, dt.month, 1) - timedelta(days=1) initial['date_from'] = df initial['date_to'] = dt initial['_fixed_rate'] = w.fixed_rate initial['_variable_rate'] = w.variable_rate return initial
def update_feed(source): ''' Updates the feeds from source if it has not been updated for UPDATE_INTERVAL hours ''' logger.info("Checking if %s needs to be updated" % str(source)) #Get the last update time if source: last_update = source.last_update updated_articles = [] logger.debug("%s was last updated: %s" % (str(source), format_datetime(last_update))) #Update only if UPDATE_INTERVAL time has elapse since the last update if not last_update or timedelta(datetime.now(tzlocal()), last_update) >= timedelta(hours=UPDATE_INTERVAL): logger.info("Updating source %s" % str(source)) feed = fp.parse(source.link) for entry in feed.get('entries'): #Try parsing the date and if it thows an exception, default to the current date try: pub_date = date.parse(entry.get('published'), default=datetime.now(tzlocal())) except: pub_date = datetime.now(tzlocal()) link = entry.get('link') heading = entry.get('title') summary = entry.get('summary_detail').get('value') logger.debug("Parsed article: %s" % u''.join(heading).encode('utf-8').strip()) #Check if article has already been added. article = get_object_or_none(Article, link=link) if not article: try: logger.debug("Article not found in database. Adding to database") article = Article.objects.create(pub_date=pub_date, link=link, source=source, heading=heading, summary=summary) article.tag_self() updated_articles.append(article) except Exception, e: logger.exception(e) #Update the last update time of this source source.last_update = datetime.now(tzlocal()) source.save() logger.info("No of articles updated: %d" % len(updated_articles))
async def __anext__(self): sleep_seconds = (self.next_run_dt - self.env.now).total_seconds() logger.debug("#Scheduler anext, now:%s next_run_dt:%s", self.env.now, self.next_run_dt) await self.env.dispatcher.sleep(sleep_seconds) if self.max_step is not None: step = random.randint(self.min_step, self.max_step) else: step = self.min_step self.run_dt = self.next_run_dt self.next_run_dt = self.run_dt + timedelta(**{self.unit: step}) return self.run_dt
def chrono(bot, irc, cur): print cur.args if not cur.args: label = bot.label t = bot.init_time diff = timedelta(datetime.now(), datetime.fromtimestamp(t)) diff_str = "%i d, %.2i h, %.2i m, %.2i s." % ( diff.days, diff.hours, diff.minutes, diff.seconds) bot.privnotice("I've join %s at %s (%s ago)", bot.label, datetime.fromtimestamp(t).strftime("%Y-%m-%d %H:%M:%S"), diff_str) else: if cur.args == "wm": label = "wikimedia" tbot = bot.thread_bots(label) t = tbot.init_time diff = timedelta(datetime.now(), datetime.fromtimestamp(t)) diff_str = "%i d, %.2i h, %.2i m, %.2i s." % ( diff.days, diff.hours, diff.minutes, diff.seconds) bot.privnotice( "I've join %s at %s (%s ago)", label, datetime.fromtimestamp(t).strftime("%Y-%m-%d %H:%M:%S"), diff_str)
def init(self): assert self.unit in Scheduler.unit_types replay_dict = {} if self.bench_dt.year < self.env.now.year: replay_dict["year"] = self.env.now.year if self.unit == "minutes": replay_dict["second"] = self.bench_dt.second if self.unit == "hours": replay_dict["minute"] = self.bench_dt.minute replay_dict["second"] = self.bench_dt.second if self.unit == "days": replay_dict["hour"] = self.bench_dt.hour replay_dict["minute"] = self.bench_dt.minute replay_dict["second"] = self.bench_dt.second if self.unit == "months": replay_dict["day"] = self.bench_dt.day replay_dict["hour"] = self.bench_dt.hour replay_dict["minute"] = self.bench_dt.minute replay_dict["second"] = self.bench_dt.second if self.unit == "years": replay_dict["month"] = self.bench_dt.month replay_dict["day"] = self.bench_dt.day replay_dict["hour"] = self.bench_dt.hour replay_dict["minute"] = self.bench_dt.minute replay_dict["second"] = self.bench_dt.second self.run_dt = self.next_run_dt = self.env.now.replace(**replay_dict) while self.next_run_dt < self.env.now: if self.max_step is not None: step = random.randint(self.min_step, self.max_step) else: step = self.min_step self.run_dt = self.next_run_dt self.next_run_dt = self.run_dt + timedelta(**{self.unit: step}) logger.debug("#Scheduler last run:%s next run:%s", self.run_dt, self.next_run_dt) return self
def put(self, request): data = loads(request.body) try: # First, validate the input data through a JSON schema InstructorCreateView.schema.validate(data) # Check if this user is not a duplicate (enroll ID is ab-so-lute) if Instructor.objects.active(user_id=data['id']).exists(): return JsonResponse({ 'version': '0.1.0', 'status': 409 }, status=409) # We need to process many queries and related stuff, so we wrap everything in a transaction with atomic(): # Create the student object instructor = Instructor( user_id=data['id'], full_name=data['general']['name'], email_address=data['general']['email-address'], availability=Availability.objects.create( expiry=now() + timedelta(days=15)), role=Role.objects.get(codename='instructor')) # Create a randomized password for the instructor for now (we will let them change it later on) password = User.objects.make_random_password( 12, allowed_chars= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) instructor.set_password(password) instructor.save() # Connect with each specialty subject - assign full confidence as default value for code in data['subjects']: Specialty.objects.create( subject=Subject.objects.get(code__iexact=code), instructor=instructor, confidence=1.0) # Send an email to the user with his/her password, as it was randomly-generated email = TemplateEmailMessage( subject=_('Your password for Project Rhea'), from_email='noreply@project_rhea.com', to=[instructor.email_address], context=RequestContext(request, { 'instructor': instructor, 'password': password })) email.attach_from_template('rhea/email/new-instructor.txt', 'text/plain') email.send() return JsonResponse( { 'version': '0.1.0', 'status': 201, 'email': email.send(fail_silently=True) == 1, 'instructor': { 'id': instructor.user_id, 'name': instructor.full_name, 'email': instructor.email_address, 'created': mktime(instructor.date_registered.utctimetuple()) } }, status=201) except ValidationError: return JsonResponse({ 'version': '0.1.0', 'status': 403 }, status=403)