Пример #1
0
def get_first_sunday(date):
    first_sunday = date
    day_index = datetime.weekday(first_sunday)
    while (day_index < 6):
        first_sunday = first_sunday + timedelta(1)
        day_index = datetime.weekday(first_sunday)
    return first_sunday
Пример #2
0
 def _compute_door_codes(self):
     for res in self:
         entrada = datetime.strptime(
             res.checkin[:10], DEFAULT_SERVER_DATE_FORMAT)
         if datetime.weekday(entrada) == 0:
             entrada = entrada + timedelta(days=1)
         salida = datetime.strptime(
             res.checkout[:10], DEFAULT_SERVER_DATE_FORMAT)
         if datetime.weekday(salida) == 0:
             salida = salida - timedelta(days=1)
         codes = (u'Código de entrada: ' +
                  '<strong><span style="font-size: 1.4em;">' +
                  res.doorcode4(datetime.strftime(entrada, "%Y-%m-%d")) +
                  '</span></strong>')
         while entrada <= salida:
             if datetime.weekday(entrada) == 0:
                 codes += ("<br>" +
                           u'Cambiará el Lunes ' +
                           datetime.strftime(entrada, "%d-%m-%Y") +
                           ' a: <strong><span style="font-size: 1.4em;">' +
                           res.doorcode4(datetime.strftime(
                               entrada, "%Y-%m-%d")) +
                           '</span></strong>')
             entrada = entrada + timedelta(days=1)
         res.door_codes = codes
Пример #3
0
    def updatePump(self):
        time = dt.now()
        currTime = (time -
                    time.replace(hour=0, minute=0, second=0)).total_seconds()

        if not self.pumpOverride:
            if self.pumpStatus:
                if currTime >= self.pumpTimes[1] or currTime < self.pumpTimes[
                        0] or dt.weekday(time) not in self.activeDays:
                    self.pumpStatus = False
                    GPIO.output(self.pin,
                                GPIO.HIGH if self.pumpStatus else GPIO.LOW)

            else:
                if self.pumpTimes[0] <= currTime < self.pumpTimes[
                        1] and dt.weekday(time) in self.activeDays:
                    self.pumpStatus = True
                    GPIO.output(self.pin,
                                GPIO.HIGH if self.pumpStatus else GPIO.LOW)

        else:
            if currTime >= self.pumpOverrideTime:
                self.setAuto()

        return self.pumpStatus
Пример #4
0
def rel_date(date):
    now = date.today()
    dt = now - date
    ampm = 'am' if date.hour < 12 else 'pm'
    hour = '%d' % (date.hour % 12 if date.hour % 12 > 0 else 12)
    time = '%s:%02d %s' % (hour, date.minute, ampm)
    if date.year != now.year:
        return '%s, %s, %d %s %d' % (time, weekdays[date.weekday()], date.day,
                                     months[date.month - 1], date.year)
    elif dt.days >= 7:
        return '%s, %s, %d %s' % (time, weekdays[date.weekday()], date.day,
                                  months[date.month - 1])
    elif dt.days > 1:
        return '%d days ago' % dt.days
    elif dt.days == 1:
        return '1 day ago'
    elif dt.seconds >= 7200:
        return '%d hours ago' % (dt.seconds // 3600)
    elif dt.seconds >= 3600:
        return '1 hour ago'
    elif dt.seconds >= 120:
        return '%d minutes ago' % (dt.seconds // 60)
    elif dt.seconds >= 60:
        return '1 minute ago'
    elif dt.seconds >= 2:
        return '%d seconds ago' % dt.seconds
    elif dt.seconds == 1:
        return '1 second ago'
    return 'Just now'
Пример #5
0
def get_current_and_next_day():
    '''Возвращает список из номера текущего дня и следующего.'''
    datetime_now = datetime.utcnow() + timedelta(hours=3)
    weekday_current = datetime.weekday(datetime_now)
    weekday_next = datetime.weekday(datetime_now + timedelta(days=1))

    return [weekday_current, weekday_next]
Пример #6
0
def auto_posting(current_time):
    today = datetime.now()
    week_type = (today.isocalendar()[1] +
                 int(config.get('bot', 'WEEK_TYPE'))) % 2

    if datetime.weekday(today) == 6:
        today += timedelta(days=1)
        week_type = (week_type + 1) % 2

    day = helpers.daysOfWeek[datetime.weekday(today)]

    # Выборка пользователей из базы у которых установлена отправка расписания на текущий день
    with ScheduleDB() as db:
        users = db.find_users_where(auto_posting_time=current_time,
                                    is_today=True)

    send_schedule(users, current_time, day, week_type)

    # Выборка пользователей из базы у которых установлена отправка расписания на завтрашний день,
    # если сегодня воскресенье, то расписание будет отправляться на понедельник.
    if datetime.weekday(datetime.now()) != 6:
        today += timedelta(days=1)

    day = helpers.daysOfWeek[datetime.weekday(today)]

    with ScheduleDB() as db:
        users = db.find_users_where(auto_posting_time=current_time,
                                    is_today=False)

    send_schedule(users, current_time, day, week_type)
Пример #7
0
def habiles(fecha1, fecha2):
    time1 = int(str(datetime.weekday(fecha1)))
    time2 = int(str(datetime.weekday(fecha2)))
    dia = time1 - time2
    diferencia = fecha2 - fecha1
    valor = int(str(diferencia.days))

    if valor >= 7:
        val = ((valor + dia) // 7) * 2
        habiles = valor - val + 1

        if time1 > 4 or time2 > 4:
            if time2 > time1:
                if time2 == 5:
                    habiles = habiles - 1
                else:
                    if time2 == 6:
                        habiles = habiles - 2
            else:
                if (time1 > time2 and time1 == 6) and time2 != 5:
                    habiles = habiles + 1
                else:
                    if time1 == time2:
                        habiles = habiles - 1
    else:
        if (time1 + valor) > 5:
            habiles = valor - 1
        else:
            if (time1 + valor) == 5:
                habiles = valor
            else:
                habiles = valor + 1

    return habiles
Пример #8
0
def day_type_of(datetime):
    if (datetime.weekday() < 5):
        return 'Laborable'
    elif (datetime.weekday() < 6):
        return 'Sabado'
    else:
        return 'Dom. y Fest.'
Пример #9
0
def habiles(fecha1, fecha2):

    time1 = int(str(datetime.weekday(fecha1)))
    time2 = int(str(datetime.weekday(fecha2)))
    dia = time1 - time2
    diferencia = fecha2 - fecha1
    valor = int(str(diferencia.days))

    if valor >= 7:
        val = ((valor + dia) // 7) * 2
        habiles = valor - val + 1

        if time1 > 4 or time2 > 4:
            if time2 > time1:
                if time2 == 5:
                    habiles = habiles - 1
                else:
                    if time2 == 6:
                        habiles = habiles - 2
            else:
                if (time1 > time2 and time1 == 6) and time2 != 5:
                    habiles = habiles + 1
                else:
                    if time1 == time2:
                        habiles = habiles - 1
    else:
        if (time1 + valor) > 5:
            habiles = valor - 1
        else:
            if (time1 + valor) == 5:
                habiles = valor
            else:
                habiles = valor + 1

    return habiles
Пример #10
0
def otchet_td(request, start_time = date.today() - timedelta(days = 10 + datetime.weekday(date.today())),
                stop_time = date.today() - timedelta(days = 3 + datetime.weekday(date.today()))):
    args = {}
    if request.GET:
        if request.GET.get('start_time'):
            start_time = datetime.strptime(request.GET.get('start_time'), '%Y-%m-%dT%H:%M')
        if request.GET.get('stop_time'):
            stop_time = datetime.strptime(request.GET.get('stop_time'), '%Y-%m-%dT%H:%M')
    args['start_time'] = start_time.strftime('%Y-%m-%dT%H:%M')
    args['stop_time'] = stop_time.strftime('%Y-%m-%dT%H:%M')
    args['fire'] = s_fault.objects.filter(fault_time__gte = start_time, fault_time__lte = stop_time, f_system = 1,)
    args['lifts'] = s_drop_lift.objects.filter(stop_lift__gte = start_time, stop_lift__lte = stop_time, fault_id = 1,)
    args['username'] = request.user.get_full_name()
    fault_sys = s_system.objects.all()
    lift = s_fault_lift.objects.all()
    fault_count ={}
    lift_count ={}
    for fau in fault_sys:
        fault_count[fau.system_name] = s_fault.objects.filter(f_system__system_name = fau.system_name,
                                                              fault_time__gte = start_time,
                                                              fault_time__lte = stop_time, ).count()
    for l in lift:
        lift_count[l.type_fault] = s_drop_lift.objects.filter(fault__type_fault = l.type_fault,
                                                              stop_lift__gte = start_time,
                                                              stop_lift__lte = stop_time, ).count()
    # print(fault_count)
    # args['f_count'] = list(fault_count.keys()).sort()
    # args['l_count'] = list(lift_count.keys()).sort()
    args['fault_count'] = OrderedDict(sorted(fault_count.items(), key=lambda t: t[0]))
    args['lift_count'] = OrderedDict(sorted(lift_count.items(), key=lambda t: t[0]))
    return render_to_response('otchet_td.html', args, context_instance=RequestContext(request))
Пример #11
0
 def last_seven_days(self):
     self.type = self.kwargs.get('type')
     now = datetime.now()
     seven_days_ago = now - timedelta(days=7)
     if self.type == 'rh':
         datas = Humidity.objects.order_by('recorded_time').filter(
             recorded_time__range=(seven_days_ago,
                                   now)).annotate(value=F('RH'))
     elif self.type == 'bp':
         datas = Pressure.objects.order_by('recorded_time').filter(
             recorded_time__range=(seven_days_ago,
                                   now)).annotate(value=F('BP'))
     else:
         datas = Temperature.objects.order_by('recorded_time').filter(
             recorded_time__range=(seven_days_ago,
                                   now)).annotate(value=F('celesius'))
     #print(str(data.recorded_time)+'='+str(weekday)+' '+ days[weekday])
     print(datas)
     for data in datas:
         weekday = datetime.weekday(data.recorded_time)
         if days[weekday] not in self.labels:
             self.labels.append(days[weekday])
     self.max_list = [-100 for i in range(len(self.labels))]
     self.min_list = [9999 for i in range(len(self.labels))]
     for data in datas:
         weekday = datetime.weekday(data.recorded_time)
         idx = self.labels.index(days[weekday])
         self.set_minmax(idx, data.value)
Пример #12
0
def diatrabalho(p=0, d=0):
    """
    -->> Retorna data util de acordo com relacao de feriados ANBIMA (ja disponibilizada pela
         funcao feriados_lista), periodo e data-base informados pelo usuario (opcionais);
         A relacao de feriados utilizada por essa funcao pode ser
         encontrada em: https://www.anbima.com.br/feriados/feriados.asp 
         Qualquer edicao dessas datas devera ser realizada dentro da funcao feriados_lista() <<--

    Args:
        p (int, optional): Intervalo desejado em DIAS UTEIS (numero inteiro)
        d (int, optional): Data-Base desejada; Manter nulo para data atual

    # IMPORTANTE: se a data-base (seja a informada ou a atual) for um dia nao-util,
        a funcao iniciara a contagem a partir do primeiro dia util anterior a esta

    Returns:
        [date]
    """

    from datetime import datetime, date, timedelta

    try:
        if d == 0:
            d = datetime.now().date()

        if type(d) == str:
            d = datetime.strptime(d, '%d/%m/%Y').date()

        if type(d) == datetime:
            d = d.date()

        if type(p) != int or p % 1 != 0:
            print(
                '[ERRO!] Informe um período em número INTEIRO. Mantenha os campos nulos para\n'
                'data atual e período = 0. Variáveis são aceitas desde que no formato adequado.'
            )
            return False

        feriados = feriados_lista()

        while d.strftime('%d/%m/%Y') in feriados or datetime.weekday(d) > 4:
            d = d + timedelta(days=-1)

        while p != 0:
            a = p / abs(p)
            d = d + timedelta(days=a)

            if d.strftime('%d/%m/%Y') in feriados or datetime.weekday(d) > 4:
                p += 0
            else:
                p -= a

    except (ValueError, TypeError, AttributeError):
        print(
            '[ERRO!] Insira uma data no formato DD/MM/AAAA (com barras e entre aspas) e um período em número INTEIRO.\n'
            'Mantenha os campos nulos para data atual e período = 0. Variáveis são aceitas desde que no formato adequado.'
        )

    return d.strftime('%d/%m/%Y')
def auto_posting(current_time):
    today = datetime.now()
    week_type = (today.isocalendar()[1] + 1) % 2

    if datetime.weekday(today) == 6:
        today += timedelta(days=1)
        week_type = (week_type + 1) % 2

    day = [helpers.daysOfWeek[datetime.weekday(today)]]

    # Выборка пользователей из базы у которых установлена отправка расписния на текущий день
    with ScheduleDB(app.config) as db:
        users = db.find_users_where(auto_posting_time=current_time, is_today=True)

    if users is None:
        return None
    try:
        count = 0
        for user in users:
            uid = user[0]
            tag = user[1]

            schedule = create_schedule_text(tag, day[0], week_type)
            vkapi.send_message(uid, app.config['TOKEN'], schedule)
            count += 1
            if count > 20:
                sleep(1)

            # Логирование
    except BaseException as e:
        pass

    # Выборка пользователей из базы у которых установлена отправка расписния на завтрашний день,
    # если сегодня воскресенье, то расписание будет отправляться на понедельник.
    if datetime.weekday(datetime.now()) != 6:
        today += timedelta(days=1)

    day = [helpers.daysOfWeek[datetime.weekday(today)]]

    with ScheduleDB(app.config) as db:
        users = db.find_users_where(auto_posting_time=current_time, is_today=False)

    if users is None:
        return None
    try:
        count = 0
        for user in users:
            uid = user[0]
            tag = user[1]

            schedule = create_schedule_text(tag, day[0], week_type)
            vkapi.send_message(uid, app.config['TOKEN'], schedule)
            count += 1
            if count > 20:
                sleep(1)

            # Логирование
    except BaseException as e:
        pass
Пример #14
0
def SimpleLastTD(lastBusDay):
    lastBusDay = lastBusDay - timedelta(days=1)
    if datetime.weekday(lastBusDay) == 5:  #if it's Saturday
        lastBusDay = lastBusDay - timedelta(days=1)  #then make it Friday
    elif datetime.weekday(lastBusDay) == 6:  #if it's Sunday
        lastBusDay = lastBusDay - timedelta(days=2)
        #then make it Friday
    return (lastBusDay)
Пример #15
0
def find_first_sunday(year):
    date = datetime(year, 1, 1, 9)
    weekday = datetime.weekday(date)

    while weekday < 6:
        date = date + timedelta(1)
        weekday = datetime.weekday(date)

    return date
Пример #16
0
def timeline(from_date='03/1/2014', output='timeline.csv'):
    import csv
    from datetime import datetime
    import pandas as pd

    open_dataset = open('trade_date.csv', 'r')
    dataset = csv.reader(open_dataset)
    date = [line for line in dataset]
    date = [datetime.strptime(point[0], '%m/%d/%Y') for point in date]

    open_dataset_1 = open('friday.csv', 'r')
    dataset = csv.reader(open_dataset_1)
    friday = [line for line in dataset]
    friday = [
        datetime.strptime(point[0], '%I:%M:%S %p').time() for point in friday
    ]

    open_dataset_2 = open('weekday.csv', 'r')
    dataset = csv.reader(open_dataset_2)
    weekday = [line for line in dataset]
    weekday = [
        datetime.strptime(point[0], '%I:%M:%S %p').time() for point in weekday
    ]

    open_dataset_3 = open('sunday.csv', 'r')
    dataset = csv.reader(open_dataset_3)
    sunday = [line for line in dataset]
    sunday = [
        datetime.strptime(point[0], '%I:%M:%S %p').time() for point in sunday
    ]

    open_dataset.close()
    open_dataset_1.close()
    open_dataset_2.close()
    open_dataset_3.close()

    from_date = datetime.strptime(from_date, '%m/%d/%Y')
    timeline = []

    for i in date:  #extract date
        if i <= from_date:
            break
        if datetime.weekday(i) == 6:
            for j in sunday:  # extract time
                timeline.append(datetime.combine(i, j))
        elif datetime.weekday(i) == 4:
            for j in friday:  # extract time
                timeline.append(datetime.combine(i, j))
        else:
            for j in weekday:  # extract time
                timeline.append(datetime.combine(i, j))

    timeline = pd.DataFrame(timeline)

    open_dataset = open(output, 'wb')  #open the target file and write in
    timeline.to_csv(open_dataset, index=False, header=False)
    open_dataset.close()
def get_init_date():
    today = datetime.today()
    date = datetime(today.year - 1, today.month, today.day, 12)
    weekday = datetime.weekday(date)

    while weekday < 6:
        date = date + timedelta(-1)
        weekday = datetime.weekday(date)

    return date
Пример #18
0
 def get_datetime(self):
     timezone = self.api.state['user']['tz_info']['timezone']
     tz_location = tz.gettz(timezone)
     now = datetime.now(tz=tz_location)
     self.weekstart = datetime.weekday(now) == self.api.state['user'][
         'start_day'] % 7  #Checks if yesterday was the week start day
     self.off_day = datetime.weekday(now) in [
         i % 7 for i in self.api.state['user']['days_off']
     ]  #Checks if yesterday was an off day
     self.today = now.strftime(TODOIST_DATE_FORMAT)
Пример #19
0
	def get(self, request, *args, **kwargs):
		if request.is_ajax():
			profile = request.user.profile if not request.user.is_anonymous() else None
			today_number = datetime.weekday(datetime.now()) 
			monday_date = datetime.today() - timedelta(days=today_number) 
			tuesday = monday_date + timedelta(days=1)
			wednesday = monday_date + timedelta(days=2)
			thursday = monday_date + timedelta(days=3)
			friday = monday_date + timedelta(days=4)
			saturday = monday_date + timedelta(days=5)
			sunday = monday_date + timedelta(days=6)

			self.object_list = self.model.objects.filter(
				Q(start__day=monday_date.day) |
				Q(start__day=tuesday.day) |
				Q(start__day=wednesday.day) |
				Q(start__day=thursday.day) |
				Q(start__day=friday.day) |
				Q(start__day=saturday.day) |
				Q(start__day=sunday.day),
				Q(guest__profile=profile) | 
				Q(is_public=True)
			).exclude(status=2).exclude(status=3)			
			
			events = []

			for event in self.object_list:
				event_day = ""
				if datetime.weekday(event.start) == datetime.weekday(date.today())+1:
					event_day = "Hoy" 
				elif datetime.weekday(event.start) == 1:
					event_day = "Lunes"
				elif datetime.weekday(event.start) == 2:
					event_day = "Martes"
				elif datetime.weekday(event.start) == 3:
					event_day = "Miercoles"
				elif datetime.weekday(event.start) == 4:
					event_day = "Jueves"
				elif datetime.weekday(event.start) == 5:
					event_day = "Viernes"
				elif datetime.weekday(event.start) == 6:
					event_day = "Sábado"
				else:
					event_day = "Domingo"

				events.append({
					'id': event.id,
					'name': event.name,
					'description': event.description,
					'latitude': event.latitude,
					'longitude': event.longitude,
					'event_image_url': event.front_image.url if event.front_image else '#',
					'event_owner': event.owner().user.username if not event.is_public else event.owner().commercial().locality.name,
					'day': event_day, #obtener el dia // if not event.is_public else event.owner().user.commercial().locality.name
					'status': event.status
				})

			return JsonResponse(events, safe=False)
		else:
			return super(EventListView, self).get(request, *args, **kwargs)
def checkio(from_date, to_date,):
    """
        Count the days of rest
    """

    daygenerator = (from_date + timedelta(x + 1) for x in range((to_date - from_date).days))
    summary = sum(1 for day in daygenerator if datetime.weekday(day) > 4)
    if datetime.weekday(from_date) == 5 or datetime.weekday(from_date) == 6:
        return summary + 1

    return summary
Пример #21
0
def num_days(start_date, end_date):
    month, day, year = start_date.split("/")
    from_date = date(int(year), int(month), int(day))
    month, day, year = end_date.split("/")
    to_date = date(int(year), int(month), int(day))
    daygenerator = (from_date + timedelta(x + 1)
                    for x in range((to_date - from_date).days))
    weekdays = sum(1 for day in daygenerator if datetime.weekday(day) < 5)
    daygenerator = (from_date + timedelta(x + 1)
                    for x in range((to_date - from_date).days))
    weekends = sum(1 for day in daygenerator if datetime.weekday(day) > 4)
    return weekdays, weekends
Пример #22
0
def get_start_date():
    """returns a datetime object for the first sunday after one year ago today
    at 12:00 noon"""
    today = datetime.today()
    date = datetime(today.year - 1, today.month, today.day, 12)
    weekday = datetime.weekday(date)

    while weekday < 6:
        date = date + timedelta(1)
        weekday = datetime.weekday(date)

    return date
Пример #23
0
def get_start_date():
    """returns a datetime object for the first sunday after one year ago today
    at 12:00 noon"""
    today = datetime.today()
    date = datetime(today.year - 1, today.month, today.day, 12)
    weekday = datetime.weekday(date)

    while weekday < 6:
        date = date + timedelta(1)
        weekday = datetime.weekday(date)

    return date
Пример #24
0
async def get_tomorrow_schedule(user_group) -> str:
    """Получить завтрашнее расписание."""
    if (datetime.weekday(datetime.now().astimezone(
            pytz.timezone("Asia/Bangkok"))) + 1 == 7):
        tomorrow = get_weekday(0)
    else:
        tomorrow = get_weekday(
            datetime.weekday(datetime.now().astimezone(
                pytz.timezone("Asia/Bangkok"))) + 1)
    if tomorrow[1] != "Воскресенье":
        answer_message = await get_schedule(user_group=user_group,
                                            day=tomorrow)
    else:
        answer_message = "*Воскресенье*\n\nЗавтра выходной! Отдыхай 😊"
    return answer_message
Пример #25
0
def order_stats():
    today = datetime.today()
    monday = today - timedelta(datetime.weekday(today))
    sunday = monday + timedelta(6)

    def stats(field, qs=None):
        """
        Stats for today, week, and month.
        """
        qs = qs or DesignOrder.objects.all()
        return (
            qs.filter(**{
                field: datetime.today,
            }).count(),

            qs.filter(**{
                '%s__range' % field: (monday, sunday)
            }).count(),

            qs.filter(**{
                '%s__month' % field: today.month,
                '%s__year' % field: today.year,
            }).count(),
        )

    return {
        'headers': ('Today', 'This Week', 'This Month'),
        'arrived': stats('arrived'),
        'completed': stats('completed'),
    }
Пример #26
0
    def is_ccdb_out_of_date(self, res_json):
        """Parse JSON describing CCDB status to determine if it is out of date.

        Returns a dict with two keys: data_down and narratives_down. Values
        for both of these are booleans.
        """
        data_down = flag_enabled('CCDB_TECHNICAL_ISSUES')
        narratives_down = False
        # show notification starting fifth business day data has not been
        # updated M-Th, data needs to have been updated 6 days ago; F-S,
        # preceding Monday
        now = datetime.now()
        weekday = datetime.weekday(now)
        delta = weekday if weekday > 3 else 6
        four_business_days_ago = (now -
                                  timedelta(delta)).strftime("%Y-%m-%d")

        try:

            if res_json['stats']['last_updated'] < four_business_days_ago:
                data_down = True
            elif (res_json['stats']['last_updated_narratives'] <
                    four_business_days_ago):
                narratives_down = True
        except KeyError:
            logger.exception("CCDB JSON status not in expected format.")

        return {
            'data_down': data_down,
            'narratives_down': narratives_down,
        }
Пример #27
0
def get_near_lesson(message):
	""" Получить ближайшее занятие """
	try:
		_, group = message.text.split()
	except:
		bot.send_message(message.chat.id, 'Это что такое? Напишите пожалуйста нормально, я вас не понимаю')
	return None
	now = datetime.now()
	day = datetime.weekday(now)
	day_p = day_c.get(day)
	time_p = tuple([now.hour, now.minute])
	count_minute_now = (time_p[0] * 60) + time_p[1]
	web_page = get_page(group)
	schedule_for_day = parse_schedule_for_a_day(web_page, day_p)
	for i in  day_c:
		if not schedule_for_day:
			day += 1
			day_p = day_c.get(day)
			time_p = tuple([now.hour, now.minute])
			count_minute_now = (time_p[0] * 60) + time_p[1]
			web_page = get_page(group)
			schedule_for_day = parse_schedule_for_a_day(web_page, day_p)
		return 
	times_lst, locations_lst, lessons_lst, aud_lst = schedule_for_day
	for i in range(len(times_lst)):
		time_s = times_lst[i].split('-')
		time_s = datetime.strptime(time_s[0], '%H:%M')
		time_s = tuple([time_s.hour, time_s.minute])
		count_minute_s = (time_s[0] * 60) + time_s[1]
	if count_minute_now < count_minute_s:
		resp = '⏰ Следущая пара:\n \n\n <b>{}</b>, {} <i>{}</i> {} \n\n'.format(times_lst[i], locations_lst[i],
		lessons_lst[i], aud_lst[i])
	return bot.send_message(message.chat.id, resp, parse_mode='HTML')
Пример #28
0
def oneDayTimetable(values):
    group = values.users[values.item['from_id']]['group']
    isUpper = values.isUpper
    message_tail = ''

    if (values.item['text'] == 'Сегодня') or (values.item['text'] == 'Завтра'):
        week = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье']
        weekday_number = datetime.weekday(datetime.now())

        if values.item['text'] == 'Завтра':
            weekday_number = (weekday_number + 1) % 7
            if weekday_number == 0:
                isUpper = not isUpper

        if week[weekday_number] in getDaysForGroup(values.timetableDict, group):
            message_tail = getTimetableByDay(values.timetableDict, group, week[weekday_number], isUpper)
    else:
        weekday = values.message.split()[1]
        message_tail = getTimetableByDay(values.timetableDict, group, weekday, None)

    if isUpper:
        message = 'Верхняя (красная, нечётная) неделя\n\n'
    else:
        message = 'Нижняя (синяя, чётная) неделя\n\n'

    if message_tail == '':
        message += 'Выходной!)'
    else:
        message += message_tail

    return message, None, get_timetable_menu_buttons(values)
    def get_object(self, data):
        data_list = []
        for timetable_obj in self.env['op.session'].browse(
                data['teacher_time_table_ids']):
            oldDate = datetime.strptime(
                timetable_obj.start_datetime, "%Y-%m-%d %H:%M:%S")
            day = datetime.weekday(oldDate)

            timetable_data = {
                'period': timetable_obj.timing_id.name,
                'period_time': timetable_obj.timing_id.hour + ':' +
                               timetable_obj.timing_id.minute +
                               timetable_obj.timing_id.am_pm,
                'sequence': timetable_obj.timing_id.sequence,
                'start_datetime': self._convert_to_local_timezone(
                    timetable_obj.start_datetime).strftime(
                    "%Y-%m-%d %H:%M:%S"),
                'end_datetime': self._convert_to_local_timezone(
                    timetable_obj.end_datetime).strftime(
                    "%Y-%m-%d %H:%M:%S"),
                'day': str(day),
                'subject': timetable_obj.subject_id.name,
                'course': timetable_obj.course_id.name,
                'batch': timetable_obj.batch_id.name,
            }
            data_list.append(timetable_data)
        ttdl = sorted(data_list, key=lambda k: k['sequence'])
        final_list = self.sort_tt(ttdl)
        return final_list
def extract_features(curr_point, previous_point):
    """
    points are given as dicts with keys (arrival_time, departure_time, lat, lng, cluster)
    """
    current_cluster = [0] * len(cluster_to_index)
    previous_cluster = [0] * len(cluster_to_index)
    current_cluster[cluster_to_index[curr_point['cluster']]] = 1
    previous_cluster[cluster_to_index[previous_point['cluster']]] = 1

    datetime = dateutil.parser.parse(curr_point['departure_time'])
    day_of_week = [-1] * 7
    day_of_week[datetime.weekday()] = 1

    hour_bin_size = 6
    hour_bin = [-1] * (24 / hour_bin_size)
    hour_bin[datetime.time().hour / hour_bin_size] = 1

    is_weekend = 1 if (day_of_week == 5 or day_of_week == 6) else -1
    ispm = 1 if datetime.time().hour >= 12 else -1
    mwf = 1 if (day_of_week == 0 or day_of_week == 2 or day_of_week == 4) else -1

    features = day_of_week + hour_bin + [is_weekend, ispm]
    features += current_cluster
    #features += previous_cluster
    return features
Пример #31
0
    def get_object(self, data):

        dayofWeek = [
            'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
        ]

        data_list = []
        for timetable_obj in pooler.get_pool(
                self.cr.dbname).get('op.timetable').browse(
                    self.cr, self.uid, data['time_table_ids']):

            oldDate = datetime.strptime(timetable_obj.start_datetime,
                                        "%Y-%m-%d %H:%M:%S")
            day = dayofWeek[datetime.weekday(oldDate)]

            timetable_data = {
                'period': timetable_obj.period_id.name,
                'sequence': timetable_obj.period_id.sequence,
                'start_datetime': timetable_obj.start_datetime,
                'day': day,
                'subject': timetable_obj.subject_id.name,
            }
            data_list.append(timetable_data)

        ttdl = sorted(data_list, key=lambda k: k['sequence'])
        final_list = self.sort_tt(ttdl)
        return final_list
    def get_object(self,data):

        dayofWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

        data_list = []
        for timetable_obj in pooler.get_pool(self.cr.dbname).get('op.timetable').browse(self.cr, self.uid, data['teacher_time_table_ids']):
            oldDate = datetime.strptime(timetable_obj.start_datetime, "%Y-%m-%d %H:%M:%S")
            day = dayofWeek[datetime.weekday(oldDate)]

            timetable_data = {
                            'period': timetable_obj.period_id.name,
                            'period_time': timetable_obj.period_id.hour + ':' + timetable_obj.period_id.minute + timetable_obj.period_id.am_pm,
                            'sequence': timetable_obj.period_id.sequence,
                            'start_datetime': timetable_obj.start_datetime[10:],
                            'end_datetime': timetable_obj.end_datetime[10:],
                            'day': day,
                            'subject': timetable_obj.subject_id.name,
##                            'faculty': self.get_full_name(timetable_obj),
#                            'faculty_middle': timetable_obj.faculty_id.middle_name,
#                            'faculty_last': timetable_obj.faculty_id.last_name,
                            'course': timetable_obj.standard_id.course_id.name,
                            'standard': timetable_obj.standard_id.name,
                             }

            data_list.append(timetable_data)
        ttdl = sorted(data_list, key=lambda k: k['sequence'])
        final_list = self.sort_tt(ttdl)
        return final_list
Пример #33
0
def list_day_from_monday_till_friday():
    """
        Список дат текущей недели с пондельника до пятницы.
        Если день субботний или воскресный, то список будет
        для следующей недели.
    """
    MONDAY = 0
    TUESDAY = 1
    WEDNESDAY = 2
    THURSDAY = 3
    FRIDAY = 4
    WEEK_LEN = 0

    day_off_week = {
        MONDAY: u'MONDAY',
        TUESDAY: u'TUESDAY',
        WEDNESDAY: u'WEDNESDAY',
        THURSDAY: u'THURSDAY',
        FRIDAY: u'FRIDAY',
    }
    now_time = datetime.now()
    current_day_off_week = datetime.weekday(now_time)
    list_day = []
    if current_day_off_week >= FRIDAY:
        WEEK_LEN = 7
    for day_num in day_off_week:
        diff_day = timedelta(days=day_num - current_day_off_week + WEEK_LEN)
        day_string_result = u'{} {}'.format(day_off_week[day_num][0:2],
                                            (now_time +
                                             diff_day).strftime(u'%Y-%m-%d'))
        simple_day = u'{}'.format((now_time + diff_day).strftime(u'%Y-%m-%d'))
        list_day.append([day_string_result, simple_day])
    return list_day
Пример #34
0
 def weekday(self):
     datetime = self.postdict.get('posttime',None)
     if datetime:
         global weekdays
         return weekdays[datetime.weekday()]
     else:
         return ""
Пример #35
0
 def _isdst(self, dt):
     tt = (dt.year, dt.month, dt.day,
           dt.hour, dt.minute, dt.second,
           dt.weekday(), 0, 0)
     stamp = _time.mktime(tt)
     tt = _time.localtime(stamp)
     return tt.tm_isdst > 0
Пример #36
0
    def get_object(self, data):

        data_list = []
        for timetable_obj in self.env['op.session'].browse(
                data['teacher_time_table_ids']):
            oldDate = datetime.strptime(
                timetable_obj.start_datetime, "%Y-%m-%d %H:%M:%S")
            day = datetime.weekday(oldDate)

            timetable_data = {
                'period': timetable_obj.timing_id.name,
                'period_time': timetable_obj.timing_id.hour + ':' +
                               timetable_obj.timing_id.minute +
                               timetable_obj.timing_id.am_pm,
                'sequence': timetable_obj.timing_id.sequence,
                'start_datetime': self._convert_to_local_timezone(
                    timetable_obj.start_datetime).strftime(
                    "%Y-%m-%d %H:%M:%S"),
                'end_datetime': self._convert_to_local_timezone(
                    timetable_obj.end_datetime).strftime(
                    "%Y-%m-%d %H:%M:%S"),
                'day': str(day),
                'subject': timetable_obj.subject_id.name,
                'course': timetable_obj.course_id.name,
                'batch': timetable_obj.batch_id.name,
            }
            data_list.append(timetable_data)

        ttdl = sorted(data_list, key=lambda k: k['sequence'])
        final_list = self.sort_tt(ttdl)
        return final_list
Пример #37
0
def infinite_request():
    ''' weekends will cause an error that I don't catch '''

    while True:

        hour = datetime.today().hour - 6
        day = datetime.weekday(datetime.today())

        #     tues-thurs           monday after 6am          friday before 3pm
        if (1 <= day <= 3) or (day == 0 and hour >= 6) or (day == 4
                                                           and hour <= 3):

            next_candle_time = _read_last_datetime(fin_symbols[0], '1')

            try:
                # First time running needs this
                if next_candle_time is None:
                    for symbol in fin_symbols:
                        finnhub_ohlc_request(symbol, '1')

                else:
                    if next_candle_time >= time.time():
                        for symbol in fin_symbols:
                            finnhub_ohlc_request(symbol, '1')

                # once the markets are open and I know things will go smoothly,
                # delete any duplicates that may have been created
                if day == 0 and hour == 9:
                    for symbol in fin_symbols:
                        _delete_duplicate_rows(symbol)

            except:
                time.sleep(5 * 60)
                infinite_request()
    def get_object(self, data):

        dayofWeek = ['Monday', 'Tuesday', 'Wednesday',
                     'Thursday', 'Friday', 'Saturday', 'Sunday']

        data_list = []
        for timetable_obj in pooler.get_pool(self.cr.dbname).get(
            'op.timetable').browse(
                self.cr, self.uid, data['time_table_ids']):

            oldDate = datetime.strptime(
                timetable_obj.start_datetime, "%Y-%m-%d %H:%M:%S")
            day = dayofWeek[datetime.weekday(oldDate)]

            timetable_data = {
                'period': timetable_obj.period_id.name,
                'sequence': timetable_obj.period_id.sequence,
                'start_datetime': timetable_obj.start_datetime,
                'day': day,
                'subject': timetable_obj.subject_id.name,
            }

            data_list.append(timetable_data)
        ttdl = sorted(data_list, key=lambda k: k['sequence'])
        final_list = self.sort_tt(ttdl)

        return final_list
Пример #39
0
def print_all(food_menu):
    '''
    Print everything from every selected restaurant from every day
    '''
    week_dates = [date.strftime('%d.%m') for date in get_current_weekdates()]

    for corp, restaurant in sorted(food_menu.items()):
        for name, week_menu in sorted(restaurant.items()):
            print(ansify('%s (%s)' % (name.capitalize(), corp.capitalize()), 'green'))

            if not week_menu:
                print(ansify(' Nothing for the whole week!', 'magenta'))

                if config.LANG.lower() == 'en':
                    print("  Maybe %s is being lazy with their english menu again?" % corp.capitalize())
                    # This shit happens way too often

            for day, day_menu in sorted(week_menu.items()):
                day = int(day)
                if not day_menu:
                    print(ansify(' Nothing found for %s (%s)' % (WEEK[day], week_dates[day]), 'magenta'))

                else:
                    if datetime.weekday(datetime.now()) == day:
                        print(ansify(' %s (%s)' % (WEEK[day], 'today'), 'red'))
                    else:
                        print(ansify(' %s (%s)' % (WEEK[day], week_dates[day]), 'magenta'))

                    for food in day_menu:
                        print("  %s" % format_food(food))

            print()  # Newline after every restaurant!
Пример #40
0
Файл: now.py Проект: kuba/SIS
    def now(self, surname):
        """
        Get the lesson for given person ``surname``.

        """
        current_order = self.current_order()
        c.lesson = None
        if current_order is None:
            return render('now/now.xml')

        today = datetime.weekday(datetime.today())
        schedule = Schedule.current()

        c.year = schedule.year

        students = Session.query(Student).\
                filter(Student.last_name.like(surname)).all()
        teachers = Session.query(Educator).\
                filter(Educator.last_name.like(surname)).all()
        people = students + teachers

        if len(people) != 1:
            c.people = people
            return render('now/list.xml')

        c.lesson = people[0].lesson(today, current_order, schedule.id)
        return render('now/now.xml')
Пример #41
0
def pre_date():
    '''
    DESCRIPTION: This function will return the previous day's date
    INPUT: Null
    OUTPUT: Previous day's date in format ready to be used in URL
    '''
    # Get today's name in number
    myday = datetime.weekday(date.today())

    # Get today's date
    today = date.today()

    #Yesterday's date
    yesterday = str(today - timedelta(days=1))

    # Extractting day month and year individually
    day = yesterday[8:]
    month = yesterday[5:7]
    year = yesterday[0:4]

    # Finding out if the previous day was a weekend for which there is no data
    if myday == 0 or myday == 6:
        print("The market was closed Yesterday")
    else:
        # The market are open on weekdays
        # The date is return in format that can be put inbetween the URL
        return day + month + year
Пример #42
0
def weekday(nodes, now):
    '[в апреле] [в следующий] [вторник]'
    offset, wday, dt = extract_values(nodes, 'delta_offset', 'weekday',
                                      'datetime')
    if not dt:
        dt = extract_values(nodes, 'date')[0]
        if not dt:
            dt = now.date()

    cat = 'datetime' if isinstance(dt, datetime) else 'date'

    dt_wday = datetime.weekday(dt)
    if (offset and offset == 1):
        days = 7 - (dt_wday - wday) % 7
    elif cat == 'date' and dt != now.date():
        days = 7 - (dt_wday - wday) % 7
    elif cat == 'datetime' and dt.date() != now.date():
        days = 7 - (dt_wday - wday) % 7
    else:
        days = wday - dt_wday
    value = dt + timedelta(days=days)
    if offset and offset == -1:
        value -= timedelta(days=7)

    return Node(nodes[0].i, cat, extract_word(nodes), value)
Пример #43
0
def set_school_days(start, end, non_instruction, dt_format):
    '''create a list of school days excluding non-instructional and weekends
    
    Args:
        start(`str`): first day of school in dt_format (e.g. YYYY/MM/DD)
        end(`str`): last day of school in dt_format
        non_instruction(`list` of `datetime`): non-instructional days
        dt_format(`str`): datetime format string (e.g. %Y/%m/%d)
        
    Returns:
        `list`'''

    start_dt = datetime.strptime(start, dt_format)
    end_dt = datetime.strptime(end, dt_format)

    delta = end_dt - start_dt

    all_days = [start_dt + timedelta(days=i) for i in range(delta.days + 1)]

    school_days = []
    #     for dt in rrule.rrule(rrule.DAILY, dtstart=start_dt, until=end_dt):
    for dt in all_days:
        if dt not in non_instruction and datetime.weekday(dt) in range(0, 5):
            school_days.append(dt)
    return school_days
Пример #44
0
    def handle(self, *args, **options):
        if datetime.weekday(date.today()) < 5:
            r =requests.get('https://zerocater.com/m/BYFJ/')
            soup = BeautifulSoup(r.text)

            def menu_scrape():
                d = datetime.isocalendar(date.today())
                today_match = date.today().isoformat()
                f = soup.find_all("div", {"data-date": today_match})
                meal_num = 1
                for x in f:
                    menu_info(x.encode('utf-8'),meal_num)
                    meal_num += 1

            def menu_info(days_soup,meal_num):
                days_soup = BeautifulSoup(days_soup)
                resturant = days_soup.find("h1", { "class" : "vendor-name"}).string[1:]
                day = date.today().isoformat()
                meal = days_soup.find("h3", { "class" : "order-name"}).string
                meal = meal.replace(u'\xa0', u' ').decode('ascii', 'ignore')
                print meal
                which_meal = meal_num
                new_meal = Meal.objects.create(meal=meal, day=day, resturant=resturant, which_meal=which_meal)
                food_items_soup = BeautifulSoup(str(days_soup.find_all("h4", { "class" : "item-name" })))
                for yummy in food_items_soup.stripped_strings:
                    if yummy != "," and yummy != "[" and yummy != "]":
                        item = yummy 
                        new_food = Food.objects.create(item=item, meal=new_meal)
                print "..............................."

            menu_scrape()
            self.stdout.write('Successfully added meal')
        else:
            pass  
    def get_object(self, data):

        dayofWeek = ['Monday', 'Tuesday', 'Wednesday',
                     'Thursday', 'Friday', 'Saturday', 'Sunday']

        data_list = []
        for timetable_obj in self.env['op.session'].browse(
                data['teacher_time_table_ids']):
            oldDate = datetime.strptime(
                timetable_obj.start_datetime, "%Y-%m-%d %H:%M:%S")
            day = dayofWeek[datetime.weekday(oldDate)]

            timetable_data = {
                'period': timetable_obj.timing_id.name,
                'period_time': timetable_obj.timing_id.hour + ':' +
                timetable_obj.timing_id.minute +
                timetable_obj.timing_id.am_pm,
                'sequence': timetable_obj.timing_id.sequence,
                'start_datetime': timetable_obj.start_datetime,
                'end_datetime': timetable_obj.end_datetime[10:],
                'day': day,
                'subject': timetable_obj.subject_id.name,
                'course': timetable_obj.course_id.name,
                'batch': timetable_obj.batch_id.name,
            }
            data_list.append(timetable_data)

        ttdl = sorted(data_list, key=lambda k: k['sequence'])
        final_list = self.sort_tt(ttdl)
        return final_list
Пример #46
0
    def get_object(self, data):

        dayofWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

        data_list = []
        for timetable_obj in (
            pooler.get_pool(self.cr.dbname).get("op.timetable").browse(self.cr, self.uid, data["time_table_ids"])
        ):

            oldDate = datetime.strptime(timetable_obj.start_datetime, "%Y-%m-%d %H:%M:%S")
            day = dayofWeek[datetime.weekday(oldDate)]

            timetable_data = {
                "period": timetable_obj.period_id.name,
                "sequence": timetable_obj.period_id.sequence,
                "start_datetime": timetable_obj.start_datetime,
                "day": day,
                "subject": timetable_obj.subject_id.name,
            }

            data_list.append(timetable_data)
        ttdl = sorted(data_list, key=lambda k: k["sequence"])
        final_list = self.sort_tt(ttdl)

        return final_list
Пример #47
0
    def get_object(self, data):

        dayofWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

        data_list = []
        for timetable_obj in (
            pooler.get_pool(self.cr.dbname)
            .get("op.timetable")
            .browse(self.cr, self.uid, data["teacher_time_table_ids"])
        ):
            oldDate = datetime.strptime(timetable_obj.start_datetime, "%Y-%m-%d %H:%M:%S")
            day = dayofWeek[datetime.weekday(oldDate)]

            timetable_data = {
                "period": timetable_obj.period_id.name,
                "period_time": timetable_obj.period_id.hour
                + ":"
                + timetable_obj.period_id.minute
                + timetable_obj.period_id.am_pm,
                "sequence": timetable_obj.period_id.sequence,
                "start_datetime": timetable_obj.start_datetime[10:],
                "end_datetime": timetable_obj.end_datetime[10:],
                "day": day,
                "subject": timetable_obj.subject_id.name,
                # 'faculty': self.get_full_name(timetable_obj),
                # 'faculty_middle': timetable_obj.faculty_id.middle_name,
                # 'faculty_last': timetable_obj.faculty_id.last_name,
                "course": timetable_obj.standard_id.course_id.name,
                "standard": timetable_obj.standard_id.name,
            }

            data_list.append(timetable_data)
        ttdl = sorted(data_list, key=lambda k: k["sequence"])
        final_list = self.sort_tt(ttdl)
        return final_list
Пример #48
0
def getAbfahrtszeiten(request):
    haltestelle_string = request.GET.get('haltestelle', 'Bahnhof')
    weekday = datetime.weekday(datetime.now())

    haltestelle = Haltestelle.objects.get(name=haltestelle_string)

    haltestellelinien = HaltestelleLinie.objects.filter(haltestelle=haltestelle)

    hsl = []
    for haltestellelinie in haltestellelinien:
        lin = {}
        lin['linie'] = haltestellelinie.linie.name

        linie = haltestellelinie.linie
        einsatzzeitenlinien = []
        for ezl in EinsatzzeitLinie.objects.filter(linie=linie):
            einsatzzeitenlinien.append(ezl)
        if weekday != '':
            for ezl in einsatzzeitenlinien:
                if ezl.einsatzzeit.bis_wochentag < weekday or weekday < ezl.einsatzzeit.von_wochentag:
                    einsatzzeitenlinien.remove(ezl)

        for ezl in einsatzzeitenlinien:
            uhrzeiten = []
            zeit = ezl.einsatzzeit.von_uhrzeit * 60
            pisszeit = ezl.einsatzzeit.bis_uhrzeit * 60
            while zeit <= pisszeit:
                uhrzeiten.append(zahl_zu_uhrzeit(zeit))
                zeit += ezl.einsatzzeit.takt
            lin['zeiten'] = uhrzeiten

        hsl.append(lin)

    return JSON_answer(hsl)
Пример #49
0
def main(workflow):
    # 检查配置信息
    if KEY is None or 32 > len(KEY):
        Configuration().set()
        return

	print("1111111")
    return
    data = get_cache_weather(workflow)
    if data is not None:
        if "ok" == data["status"]:
            # 显示地址,减少重复显示
            location = ""
            for index in ["admin_area", "parent_city", "location"]:
                if data["basic"][index] not in location:
                    location = "%s-%s" % (location, data["basic"][index])
            location = location.lstrip("-")
            # 当前天气
            today = data["now"]
            title = r"%s 现在 %s" % (location, today["cond_txt"])
            subtitle = r"温度 %s℃ | 湿度 %s%% | 能见度 %sKm | %s %s" % (today["tmp"], today["hum"], today["vis"], today["wind_dir"], today["wind_sc"])
            icon = r"icons/%s.png" % today["cond_code"]
            workflow.add_item(title=title, subtitle=subtitle, valid=False, icon=icon)
            # 未来天气
            for item in data["daily_forecast"]:
                week = get_week(datetime.weekday(datetime.strptime(item["date"], "%Y-%m-%d")))
                title = r"%s %s 白天-%s 夜间-%s" % (location, week, item["cond_txt_d"], item["cond_txt_n"])
                subtitle = r"温度 %s℃~%s℃ | 湿度 %s%% | 能见度 %sKm | %s %s" % (item["tmp_max"], item["tmp_min"], item["hum"], item["vis"], item["wind_dir"], item["wind_sc"])
                icon = r"icons/%s.png" % item["cond_code_d"]
                workflow.add_item(title=title, subtitle=subtitle, valid=False, icon=icon)
        else:
            workflow.add_item(r"暂没有 '%s' 的信息" % search, icon=ICON_ERROR)
    workflow.send_feedback()
Пример #50
0
    def _get_tradedaytoday(self):
        base_time = 190000  # 下午7點190000
        today_time = self.todaytime
        today_date = today_time.date()
        closed_days = []

        print('正在連線證交所取得交易日期清單。')
        try:
            resp = requests.get('https://www.twse.com.tw/holidaySchedule/holidaySchedule?response=csv', headers=self.tpex_headers)
            resp.encoding = 'big5'
        except Exception as e:
            print('程式結束。錯誤訊息:%s。因為連線交易日期網址的主機無法回應,連線嘗試失敗。' % e)
            sys.exit(1)
        holidays_csv = resp.text.replace('"','')
        holidays_readlines = holidays_csv.split('\n')
        for holiday_line in holidays_readlines:
            holiday_column = holiday_line.split(',')
            if (len(holiday_column) > 1) and (holiday_column[4] != 'o'):
                holiday_value = holiday_column[1]  # [1] 為[日期]  = ['名稱', '日期', '星期', '說明', '備註(* : 市場無交易,僅辦理結算交割...。o : 交易日。)']
                if re.match(r'\d+月\d+日', holiday_value):
                    each_holiday_lines = re.findall(r'\d+月\d+日', holiday_value)
                    for each_holiday in each_holiday_lines:
                        _mon = each_holiday[:each_holiday.find('月')]
                        _day = each_holiday[each_holiday.find('月')+1:each_holiday.find('日')]
                        closed_days.append(datetime(today_date.year, int(_mon), int(_day)).date())
        nTimehms = int(today_time.strftime('%H%M%S'))
        day_offset = 0
        if nTimehms < base_time:
            day_offset = 1
        trading_day = today_date - relativedelta(days=day_offset)
        while (trading_day in closed_days) or (datetime.weekday(trading_day)>4):
            day_offset += 1
            trading_day = today_date - relativedelta(days=day_offset)
        print('今天目前為止最後一個有收盤資料的交易日為: %s' % trading_day)
        return trading_day
Пример #51
0
Файл: now.py Проект: kuba/SIS
    def now(self, surname):
        """
        Get the lesson for given person ``surname``.

        """
        current_order = self.current_order()
        c.lesson = None
        if current_order is None:
            return render('now/now.xml')

        today = datetime.weekday(datetime.today())
        schedule = Schedule.current()

        c.year = schedule.year

        students = Session.query(Student).\
                filter(Student.last_name.like(surname)).all()
        teachers = Session.query(Educator).\
                filter(Educator.last_name.like(surname)).all()
        people = students + teachers

        if len(people) != 1:
            c.people = people
            return render('now/list.xml')

        c.lesson = people[0].lesson(today, current_order, schedule.id)
        return render('now/now.xml')
Пример #52
0
def json_data(request):
    from datetime import datetime, timedelta
    today = datetime.today()
    dow = datetime.weekday(today)
    startDate = today-timedelta(dow)
    thisWeek = [startDate + timedelta(x) for x in range(5)]
    c = {}
    us = request.GET.get('user')
    foods=[]
    date = request.GET.get('date')
    if request.GET.get('all_food'):
        for x in Food.objects.all():
            foods.append({"name":x.name, "description":x.description, "food_type":x.food_type,\
                "snowmen":x.get_snowmen, "puddles":x.get_puddles,\
                "options":{"gluten":x.gluten, "onions":x.onions, \
                "nuts":x.nuts, "vegetarian":x.vegetarian,\
                "dairy":x.dairy}})

        return {'foods': foods}
    elif us and date:
        users = User.objects.filter(ldap_name='zak').all()
        if users:
            u = users[0]
            c['week'] = []
            for day in thisWeek:
                print day
                mt = Menu.objects.filter(date=datetime.strftime(day,'%Y-%m-%d')).all()
                if mt:
                    menuToday = mt[0]
                    todaysMenu = {'date':datetime.strftime(day,'%Y-%m-%d')}
                    todaysMenu['comments'] = []
                    todaysMenu['foods'] = []
                    for comment in Comment.objects.filter(menu=menuToday).all():
                        theComments = {'user':comment.user.ldap_name, \
                                'comment':comment.comment}
                        theComments['snowmen'] = comment.get_snowmen
                        theComments['puddles'] = comment.get_puddles
                        todaysMenu['comments'].append(theComments)
                    for food in menuToday.foods.all():
                        foodDict = {}
                        foodDict['name'] = food.name
                        foodDict['description'] = food.description
                        foodDict['food_type'] = food.food_type
                        foodDict['gluten'] = food.gluten
                        foodDict['onions'] = food.onions
                        foodDict['vegetarian'] = food.vegetarian
                        foodDict['nuts'] = food.nuts
                        foodDict['dairy'] = food.dairy
                        foodDict['snowmen'] = food.get_snowmen
                        foodDict['puddles'] = food.get_puddles
                        todaysMenu['foods'].append(foodDict)

                    c['week'].append(todaysMenu)
            return {'week':c['week']}
        else:
            return {'week':''}
                    
    else:
        return c
Пример #53
0
def payment_dates(dateval, step):
    #step = (input('How often does this instrument pay a cash flow?  '))
    #Steps in number of months or years
    # e.g. '6m', '3m', '2y'
    #dateval = BankDate(input('What is the maturity date of this instrument?   '))
    #dateval as maturity date of instrument
    new_dates = []
    for date in daterange(dateval, step ='6m'):
        if datetime.weekday(date) == 6:
            date = date + '1d'
            new_dates.append(date)
        elif datetime.weekday(date) == 5:
            date = date + '2d'
            new_dates.append(date)
        else:
            new_dates.append(date)
    return(new_dates)
Пример #54
0
def get_scheduler_current_timestamp():
    year    = int(str(datetime.today())[:4])
    month   = int(str(datetime.today())[5:7])
    weekday = datetime.weekday(datetime.today())
    date    = int(str(datetime.today())[8:10])
    hour    = int(str(datetime.today())[11:13])
    min     = int(str(datetime.today())[14:16])
# Return year, month, Weekday, date, hour and min based on today's datetime
    return (year, month, weekday, date, hour, min)
def get_previous_bydays(dayname, start_date=None):
    if start_date is None:
        start_date = datetime.today()
    day_num = datetime.weekday(start_date)
    dat_num_target = weekdays.index(dayname)
    days_ago = (day_num - dat_num_target + 7) % 7
    if days_ago == 0:
        days_ago = 7
    return start_date - timedelta(days=days_ago)
Пример #56
0
 def _dedline_start(self, cr, uid, ids, field_name, arg, context):
     result = {}
     obj = self.browse(cr, uid, ids, context=context)[0]
     start_line = datetime.now(pytz.utc)
     if obj.pay_day and obj.prep_days > 0:
         start_date = datetime.strptime(obj.pay_day, "%Y-%m-%d %H:%M:%S").replace(tzinfo=pytz.utc)
         start_line = start_date
         count = 0
         while count < obj.prep_days:
             if datetime.weekday(start_line + timedelta(days=1)) == 5:
                 start_line = start_line + timedelta(days=3)
             elif datetime.weekday(start_line + timedelta(days=1)) == 6:
                 start_line = start_line + timedelta(days=2)
             else:
                 start_line = start_line + timedelta(days=1)
             count += 1
     result[obj.id] = start_line
     return result
Пример #57
0
def main (request):
	#for "privileged" users we show all information
	if request.user.is_authenticated and request.user.is_active:
		context = context_return()
		subform = SubscribeForm(request.POST or None)
		context['subform'] = subform
		if request.method == 'POST' and subform.is_valid():
			rp = request.POST
			subscribtion(rp)
		return render(request, 'index.html', context)
	else:
		#for new users or it they inactive(unpayed) we check out the time
		# let's compare some dates with other certain hours and minutes
		nowdate = datetime.now()
		td = datetime.weekday(nowdate)
		print(nowdate)
		comparetime_one = nowdate+relativedelta(hour=10)
		comparetime_two = nowdate+relativedelta(hour=11, minute=30)
		comparetime_three = nowdate+relativedelta(hour=14)
		comparetime_four = nowdate+relativedelta(hour=15, minute=30)
		#if time is between 10.00am and 11.30am and today is not a weekend
		#show only three past recommendations, and the remaining time
		if nowdate>=comparetime_one and nowdate<=comparetime_two and td!=5 and td!=6:
			context = cutted_context()
			subform = SubscribeForm(request.POST or None)
			context['subform'] = subform
			counter = comparetime_two-nowdate
			context['counter'] = str(counter)[2:4]
			context['counter2'] = str(counter)[0:1]
		#dont forget about subscribtion form
			if request.method == 'POST' and subform.is_valid():
				rp = request.POST
				subscribtion(rp)
			return render(request, 'indexp.html', context)
		#if time is between other interval, also must not be a weekend
		elif nowdate>=comparetime_three and nowdate<=comparetime_four and td!=5 and td!=6:
			context = cutted_context()
			subform = SubscribeForm(request.POST or None)
			context['subform'] = subform
			counter = comparetime_four-nowdate
			context['counter'] = str(counter)[2:4]
			context['counter2'] = str(counter)[0:1]
		#of course, subscribtion form
			if request.method == 'POST' and subform.is_valid():
				rp = request.POST
				subscribtion(rp)
			return render(request, 'indexp.html', context)
		#in the rest of time, show all the information, as if the user is active
		else:
			context = context_return()
			subform = SubscribeForm(request.POST or None)
			context['subform'] = subform
			if request.method == 'POST' and subform.is_valid():
				rp = request.POST
				subscribtion(rp)
			return render(request, 'index.html', context)
Пример #58
0
def get_one_period(date, weekly_pattern, begin_time, end_time, time_zone):
    week_day = datetime.weekday(date)
    if (len(weekly_pattern) > week_day) and (weekly_pattern[week_day] == '1'):
        begin_datetime = get_utc_datetime_by_zone(datetime.combine(date, begin_time), time_zone)
        if end_time < begin_time:
            date += timedelta(days=1)
        end_datetime = get_utc_datetime_by_zone(datetime.combine(date, end_time), time_zone)
        period = (begin_datetime, end_datetime)
        return period
    return None
def lastDrawTime():
    #finds last wednesday
    today = datetime.now() 
    wednesday = (datetime.weekday(today) - 3) % 7    
    last_wednesday = today - timedelta(days=wednesday)
    
    #finds last saturday 
    saturday = (datetime.weekday(today) - 6) % 7
    last_saturday = today - timedelta(days=saturday)

    #tests to find last drawing time
    if today-last_wednesday < today-last_saturday:
        date = formatday(last_wednesday)        
    elif today-last_wednesday > today-last_saturday:
        date = formatday(last_saturday)
    else:
        print "something went wrong"
    
    return date
Пример #60
0
 def get(self):
   today_db = db.GqlQuery("SELECT * FROM Signin WHERE created >= DATETIME(:earlier_this_morning) ORDER BY created desc LIMIT 1000",
     earlier_this_morning=(datetime.now(Pacific()).strftime("%Y-%m-%d 00:00:00")))
   today_count = today_db.count()
   if today_count > 1:
     today_count_signigicant = True
   dayofWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
   oldDate = datetime.now(Pacific())
   day = dayofWeek[datetime.weekday(oldDate)]
   self.response.out.write(template.render('templates/main.html', locals()))