def meetup_day(year, month, day, catagory):
	days = {'Monday':1, 'Tuesday':2, 'Wednesday':3, 'Thursday':4, 'Friday':5, 'Saturday':6, 'Sunday':7}
	total = monthrange(year, month)
	teen = [13, 14, 15, 16, 17, 18, 19]
	if catagory == 'teenth':
		for i in range(13, 20):
			testDate = date(year, month, i)
			if date.isoweekday(testDate) == days[day]:
				return date(year, month, i)
	elif catagory == '1st' or catagory == '2nd' or catagory == '3rd' or catagory == '4th' or catagory == 'last':
		nthDay = []
		for i in range(1, (total[1] + 1)):
			testDate = date(year, month, i)
			if date.isoweekday(testDate) == days[day]:
				nthDay.append(i)
		if catagory == '1st':
			return date(year, month, nthDay[0])
		elif catagory == '2nd':
			return date(year, month, nthDay[1])
		elif catagory == '3rd':
			return date(year, month, nthDay[2])
		elif catagory == '4th':
			return date(year, month, nthDay[3])
		elif catagory == 'last':
			return date(year, month, nthDay[-1])
	else:
		return 'Error, incorrect format'
Exemple #2
0
def get_day_num():
    """
    Modifies date.isoweekday() to conform with list ordering
    :return:
    """
    return date.isoweekday(
        date.today()) if date.isoweekday(date.today()) != 7 else 0
Exemple #3
0
 def _get_number_of_days2(self, date_from, date_to):
     DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
     day_from = datetime.strptime(date_from, DATETIME_FORMAT)
     day_to = datetime.strptime(date_to, DATETIME_FORMAT)
     nb_of_days = (day_to - day_from).days + 1
     bob = 0
     for day in range(0, nb_of_days):
         date = (day_from + timedelta(days=day))
         isNonWorkingDay = date.isoweekday() == 6 or date.isoweekday() == 7
         if isNonWorkingDay:
             non = bob
             bob = non + 1
     diff_day = (nb_of_days - 1) - bob
     return diff_day
Exemple #4
0
 def _get_number_of_days2(self,date_from, date_to):
     DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
     day_from = datetime.strptime(date_from,DATETIME_FORMAT)
     day_to = datetime.strptime(date_to,DATETIME_FORMAT)
     nb_of_days = (day_to - day_from).days + 1        
     bob=0
     for day in range(0, nb_of_days):  
         date = (day_from + timedelta(days=day)) 
         isNonWorkingDay = date.isoweekday()==6 or date.isoweekday()==7      
         if isNonWorkingDay :
             non=bob
             bob=non+1
     diff_day = (nb_of_days - 1) - bob
     return diff_day
Exemple #5
0
    def validate_trade_date(self, trade_date):
        # Check if the trade exists.
        timestamp = WatchlistItems.query.\
                    with_entities(WatchlistItems.created_timestamp).\
                    filter_by(id=self.order_id.data).\
                    first()
        if timestamp is None:
            return True
        trade_date = trade_date.data
        max_date = default_date()

        # Users can amend dates up to 100 days prior to the created_timestamp.
        lowest_date = timestamp[0] - timedelta(days=100)

        try:
            day_of_week = date.isoweekday(trade_date)
        except TypeError:
            raise v.ValidationError("Not a valid datetime value.")

        if trade_date > max_date:
            raise v.ValidationError("The trade and time cannot be a "
                                    "date in the future")
        elif trade_date < lowest_date:
            raise v.ValidationError("The trade and time must be within 100 "
                                    "days of the order creation date")
        elif day_of_week == 6 or day_of_week == 7:
            raise v.ValidationError("The trade date cannot fall on weekends.")
Exemple #6
0
def check_one_page(contract_code, park_id, park_name, start_date, start_idx):
  sites = []
  try:
    params = {
      'calarvdate': start_date.strftime('%m/%d/%Y'),
      'startIdx': start_idx,
      'contractCode': contract_code,
      'parkId': park_id,
      'sitepage':'true',
      'page':'calendar'
    }
    url = SITE + '/campsiteCalendar.do?' + urllib.urlencode(params)
    html = zlib.decompress(opener.open(url).read(), 16 + zlib.MAX_WBITS)

    soup = BeautifulSoup(html, 'html.parser')
    body = soup.find('table', id='calendar').find('tbody')
    for tr in body.findChildren('tr'):
      if not tr.attrs:
        tds = tr.findChildren('td')
        site_num = tds[0].find('img')['title']
        loop_name = tds[1].find('div', {'class', 'loopName'}).text
        cells = tds[2:]
        for idx, cell in enumerate(cells):
          if 'a' in cell.attrs['class']:
            date = start_date + timedelta(days=idx)
            book_url = SITE + cell.find('a')['href']
            print site_num, loop_name, date, date.isoweekday()
            site = AvailableSite(park_name, site_num, loop_name, date, book_url)
            sites.append(site)
  except Exception as e:
    print e
  return sites
    def get(self, request, format=None):
        user = self.request.user

        today = datetime.today()
        day = date.isoweekday(today)

        question = Question.objects.filter(day=day).last()
        question_serializer = QuestionSerializer(question)

        today_min = datetime.combine(timezone.now().date(),
                                     datetime.today().time().min)
        today_max = datetime.combine(timezone.now().date(),
                                     datetime.today().time().max)

        answer = Answer.objects.filter(user=user,
                                       created__range=(today_min,
                                                       today_max)).first()
        answer_serializer = AnswerSerializer(answer)
        if answer:
            is_answered = True
            data = {
                'question': question_serializer.data,
                'is_answered': is_answered,
                'answer': answer_serializer.data
            }
            return Response(data)
        else:
            is_answered = False
            data = {
                'question': question_serializer.data,
                'is_answered': is_answered,
                'answer': None
            }
            return Response(data)
Exemple #8
0
def dayofweek_pro(dataset):
    loc = dataset.copy()
    loc = loc[loc['year'] == 2018]
    #flag = pd.read_csv(r"G:\shanghaimotor\code\flag2019.csv")
    #loc = loc[loc['vin'].isin(list(flag['vin']))]
    loc = loc.drop_duplicates(['vin', 'year', 'month', 'day'])
    loc['record_time'] = loc['record_time'].apply(lambda x:str(x))
    loc['record_time'] = loc['record_time'].apply(lambda x:datetime.strptime(x, "%Y-%m-%d %H:%M:%S"))
    loc['dayofweek'] = loc['record_time'].apply(lambda x:date.isoweekday(x))
    dayofweek_day = pd.DataFrame(columns=['vin', 'weekdays', 'weekends', 'weekdays_pro', 'weekends_pro'])
    j = 0
    for vin in tqdm(loc['vin'].unique()):
        wd = 0
        wk = 0
        dt_user = loc[loc['vin'] == vin]
        dt_user.reset_index(drop=True, inplace=True)
        for i in range(len(dt_user)):
            day = dt_user.loc[i, 'dayofweek']
            if (day == 6) | (day == 7):
                wk += 1
            else:
                wd += 1
        dayofweek_day.loc[j, 'vin'] = vin
        dayofweek_day.loc[j, 'weekdays'] = wd
        dayofweek_day.loc[j, 'weekends'] = wk
        dayofweek_day.loc[j, 'weekdays_pro'] = (wd / (wd + wk))
        dayofweek_day.loc[j, 'weekends_pro'] = (wk / (wd + wk))  
        j += 1
    return(dayofweek_day)
Exemple #9
0
def weekdays_weekends(dataset):
    ww = dataset.copy()
    add_timestamp(ww)
    ww['weekday'] = ww['record_time'].apply(lambda x:date.isoweekday(x))
    ww['isweekend'] = ww['weekday'].apply(lambda x:1 if((x==6)|(x==7)) else 0)
    ww.drop('weekday', axis=1, inplace=True)
    weekdays = ww[ww['isweekend'] == 0]
    weekends = ww[ww['isweekend'] == 1]
    weekdays = weekdays.groupby(['vin', 'year', 'month', 'day']).count()
    weekdays.reset_index(inplace=True)
    weekdays = weekdays.loc[:,('vin', 'record_time')]
    weekends = weekends.groupby(['vin', 'year', 'month', 'day']).count()
    weekends.reset_index(inplace=True)
    weekends = weekends.loc[:,('vin', 'record_time')]    
    weekdays = weekdays.groupby('vin').mean()
    weekends = weekends.groupby('vin').mean()
    weekdays.reset_index(inplace=True)
    weekends.reset_index(inplace=True)
    weekdays.columns = ['vin', 'weekdays_count']
    weekends.columns = ['vin', 'weekends_count']
    ww = pd.merge(weekdays, weekends, on='vin', how='outer')
    ww = ww.fillna(0)
    ww['weekdays_weekends'] = ww['weekdays_count'] - ww['weekends_count']
    ww = ww.loc[:,('vin', 'weekdays_weekends')]
    return(ww)
Exemple #10
0
def get_times(path):
    import pandas as pd
    from datetime import datetime
    from datetime import date
    user = pd.read_excel(path, sheetname=0, header=1)

    #统计发言时间
    time1 = user[u'/基本信息/item/时间']
    pattern = re.compile(r'\d{4}-\d+-\d+ \d{2}:\d{2}')
    time_1 = []
    for time in time1:
        if type(time) == unicode:
            res = pattern.match(time)
            if res:
                time_1.append(res.group())

    times = []
    for time in time_1:
        #将发言时间转化为datetime格式
        times.append(datetime.strptime(time, "%Y-%m-%d %H:%M"))

    weekdays = []
    for time in times:
        weekdays.append(date.isoweekday(time))
    weekdays_count = pd.Series(weekdays).value_counts()

    hours = []
    for time in times:
        hours.append(time.strftime('%H'))
    hours_count = pd.Series(hours).value_counts()

    return weekdays_count, hours_count
Exemple #11
0
    def isHoliday(self, date):
        
        #split date into components fand easy readability in holiday rules below
        w = date.isoweekday() #where Monday is 1 and Sunday is 7
        m = date.month          #Between 1 and 12 inclusive.
        d = date.day    #Between 1 and the number of days in the given month of the given year.
        y = date.year            #Between MINYEAR and MAXYEAR inclusive.
        es = self.EasterSunday(y)
        dayoffset = pd.offsets.Day(1)

        holiday =   (
            # New Year's Day
            (d == 1 and m == January)
            # Good Friday
            or (date== es-2*dayoffset)
            # Easter Monday
            or (date == es + dayoffset)
            # Labour Day
            or (d == 1 and m == May)
            # Assumption
            or (d == 15 and m == August)
            # Christmas' Eve
            or (d == 24 and m == December)
            # Christmas
            or (d == 25 and m == December)
            # St. Stephen
            or (d == 26 and m == December)
            # New Year's Eve
            or (d == 31 and m == December))

        return holiday
Exemple #12
0
    def isHoliday(self, date):
        
        #split date into components fand easy readability in holiday rules below
        w = date.isoweekday() #where Monday is 1 and Sunday is 7
        m = date.month          #Between 1 and 12 inclusive.
        d = date.day    #Between 1 and the number of days in the given month of the given year.
        y = date.year            #Between MINYEAR and MAXYEAR inclusive.
        es = self.EasterSunday(y)
        dayoffset = pd.offsets.Day(1)

        holiday =   (
            # New Year's Day (possibly moved to Monday)
            ((d == 1 or (d == 2 and w == Monday)) and m == January)
            # Family Day (third Monday in February, since 2008)
            or ((d >= 15 and d <= 21) and w == Monday and m == February and y >= 2008)
            # Good Friday
            or (date == es-2 * dayoffset)
            # The Monday on or preceding 24 May (Victoria Day)
            or (d > 17 and d <= 24 and w == Monday and m == May)
            # July 1st, possibly moved to Monday (Canada Day)
            or ((d == 1 or ((d == 2 or d == 3) and w == Monday)) and m==July)
            # first Monday of August (Provincial Holiday)
            or (d <= 7 and w == Monday and m == August)
            # first Monday of September (Labor Day)
            or (d <= 7 and w == Monday and m == September)
            # second Monday of October (Thanksgiving Day)
            or (d > 7 and d <= 14 and w == Monday and m == October)
            # Christmas (possibly moved to Monday or Tuesday)
            or ((d == 25 or (d == 27 and (w == Monday or w == Tuesday))) and m == December)
            # Boxing Day (possibly moved to Monday or Tuesday)
            or ((d == 26 or (d == 28 and (w == Monday or w == Tuesday))) and m == December)
            )

        return holiday
Exemple #13
0
    def isHoliday(self, date):
        
        #split date into components fand easy readability in holiday rules below
        w = date.isoweekday() #where Monday is 1 and Sunday is 7
        m = date.month          #Between 1 and 12 inclusive.
        d = date.day    #Between 1 and the number of days in the given month of the given year.
        y = date.year            #Between MINYEAR and MAXYEAR inclusive.
        es = self.EasterSunday(y)
        dayoffset = pd.offsets.Day(1)

        holiday =   (
    
            # New Year's Day (possibly moved to Monday)
            (d == 1  and m == January)
            # Australia Day, January 26th (possibly moved to Monday)
            or ((d == 26 or ((d == 27 or d == 28) and w == Monday)) and m == January)
            #Good Friday
            or (date == es - 2*dayoffset)
            #Easter Monday
            or (date == es + dayoffset)
            # ANZAC Day, April 25th (possibly moved to Monday)
            or ((d == 25 or (d == 26 and w == Monday)) and m == April)
            # Queen's Birthday, second Monday in June
            or ((d > 7 and d <= 14) and w == Monday and m == June)
            # Bank Holiday, first Monday in August
            or (d <= 7 and w == Monday and m == August)
            # Labour Day, first Monday in October
            or (d <= 7 and w == Monday and m == October)
            # Christmas, December 25th (possibly Monday or Tuesday)
            or ((d == 25 or (d == 27 and (w == Monday or w == Tuesday))) and m == December)
            # Boxing Day, December 26th (possibly Monday or Tuesday)
            or ((d == 26 or (d == 28 and (w == Monday or w == Tuesday))) and m == December)
            )

        return holiday
Exemple #14
0
def get_last_weekday(weekday_iso_number, in_future=False, from_date=None):
    """Gets datetime object for the last ISO Weekday (1=Monday, 7=Sunday).
        If in_future is True, the Weekday is not the last, but the next.

        If today is Weekday, return today. If in_future, return the next Weekday.

        from_date should be date
        """

    if from_date:
        if isinstance(from_date, datetime):
            from_date = from_date.date()
        if not isinstance(from_date, date):
            raise ValueError("from_date should be date or at least datetime")
        date = from_date
    else:
        date = datetime.now().date()
    date_day_number = date.isoweekday()

    if date_day_number >= weekday_iso_number:
        if in_future:
            return date + timedelta(days=7 - date_day_number +
                                    weekday_iso_number)
        else:
            return date + timedelta(days=weekday_iso_number - date_day_number)
    else:
        if in_future:
            return date + timedelta(days=weekday_iso_number - date_day_number)
        else:
            return date + timedelta(days=-date_day_number -
                                    (7 - weekday_iso_number))
Exemple #15
0
    def isHoliday(self, date):
        #  split date into components fand easy readability in holiday rules below
        w = date.isoweekday() #where Monday is 1 and Sunday is 7
        m = date.month          #Between 1 and 12 inclusive.
        d = date.day    #Between 1 and the number of days in the given month of the given year.
        y = date.year            #Between MINYEAR and MAXYEAR inclusive.
        es = self.EasterSunday(y)
        dayoffset = pd.offsets.Day(1)

        holiday =   (
            # New Year's Day (possibly moved to Monday)
            ((d == 1 or ((d == 2 or d == 3) and w == Monday)) and m == January)
            #Good Friday
            or (date == es - 2*dayoffset)
            #Easter Monday
            or (date == es + dayoffset)
            #first Monday of May (Early May Bank Holiday)
            or (d <= 7 and w == Monday and m == May)
            #last Monday of May (Spring Bank Holiday)
            or (d >= 25 and w == Monday and m == May and y != 2002)
            #last Monday of August (Summer Bank Holiday)
            or (d >= 25 and w == Monday and m == August)
            # Christmas (possibly moved to Monday and Tuesday)
            or ((d == 25 or (d == 27 and (w == Monday or w == Tuesday))) and m == December)
            #Boxing Day (possibly moved to Monday and Tuesday)
            or ((d == 26 or (d == 28 and (w == Monday or w == Tuesday))) and m == December)
            #June 3rd, 2002 only (Golden Jubilee Bank Holiday)
            #June 4rd, 2002 only (special Spring Bank Holiday)
            or ((d == 3 or d == 4) and m == June and y == 2002)
            #June 5th, 2012 only (Diamond Jubilee Bank Holiday)
            or (d == 5 and m == June and y == 2012)
            #December 31st, 1999 only
            or (d == 31 and m == December and y == 1999))
            
        return holiday
def main():

	# Default returns information from the last week
	config_init()
	mixpanel_main()
	alexa_main()
	klout_main()
	twitter_main() # Twitter information doesn't change week to week
	github_main() # Github information doesn't change week to week
	google_analytics_main()
	if (date.isoweekday(date.today()) == 7) or (date.isoweekday(date.today()) == 1):
		client = spreadsheet_auth()
		weekly_ss_recorder(client)
	if (date.today().day == 1):
		client = spreadsheet_auth()
		monthly_ss_recorder(client)
Exemple #17
0
def isLocValid(loc_point,
               show_all_days=True,
               valid_day_of_week=1,
               show_full_range=True,
               min_lat_range=40.495992,
               max_lat_range=40.915568,
               min_lon_range=-74.257159,
               max_lon_range=-73.699215,
               include_traveling=True,
               include_stationary=True
               ):
    if (not show_all_days) and date.isoweekday(
            date.fromtimestamp(int(loc_point.get('timestampMs')) / 1000)) != valid_day_of_week:
        return False
    lat = loc_point.get('latitudeE7') * 1e-7
    lon = loc_point.get('longitudeE7') * 1e-7
    if (not show_full_range) and (not (min_lat_range < lat < max_lat_range and min_lon_range < lon < max_lon_range)):
        return False
    velocity = loc_point.get('velocity')
    is_traveling = type(velocity) is int and velocity > 0
    if is_traveling and not include_traveling:
        return False
    if (not is_traveling) and not include_stationary:
        return False
    return True
Exemple #18
0
    def handle_email_flag(self):
        if self.flag:
            # Send email
            now_day = date.isoweekday(datetime.now())
            now_hour = datetime.now().hour
            if now_day in self.EMAIL_WORKING_DAYS and now_hour in self.EMAIL_WORKING_HOURS:
                self.EMAIL_KWARGS['subject'] = '%s %s #scrapydweb' % (
                    self.flag, self.job_key)
                self.EMAIL_KWARGS['content'] = self.json_dumps(
                    self.email_content_kwargs, sort_keys=False)

                args = [
                    sys.executable,
                    os.path.join(os.path.dirname(CWD), 'utils',
                                 'send_email.py'),
                    self.json_dumps(self.EMAIL_KWARGS)
                ]
                self.logger.info("Sending email: %s" %
                                 self.EMAIL_KWARGS['subject'])
                Popen(args)

            # Update self.job_data_dict (last_send_timestamp would be updated only when flag is non-empty)
            self.logger.debug(self.job_data_dict[self.job_key])
            self.job_data_dict[self.job_key] = (self.job_stats,
                                                self.triggered_list,
                                                self.has_been_stopped,
                                                time.time())
            self.logger.debug(self.job_data_dict[self.job_key])

        if self.job_finished:
            self.job_data_dict.pop(self.job_key)
            if len(self.job_finished_set) > 1000:
                self.job_finished_set.clear()
            self.job_finished_set.add(self.job_key)
Exemple #19
0
def get_weekday(input_date):
    s = input_date.split("-")
    year = int(s[0])
    month = int(s[1])
    day = int(s[2])
    weekdays = [u"星期一", u"星期二", u"星期三", u"星期四", u"星期五", u"星期六", u"星期日"]
    return weekdays[date.isoweekday(date(year, month, day)) - 1]
    def return_date_time(self, check):
        start_low = datetime(1900, 1, 1, 0, 0).time()
        start_high = datetime(1900, 1, 1, 8, 0).time()
        end_low = datetime(1900, 1, 1, 20, 0).time()
        end_high = datetime(1900, 1, 1, 23, 59).time()

        if start_low < check.time() < start_high:
            if (check.isoweekday() == 7):
                date = check + timedelta(days=1)
                add_speech = "Since its not possible to reserve room on Sunday, the search was done for Monday 8:00 a.m."
            else:
                date = check
                add_speech = "Since its not possible to reserve room now, the search was done for 8:00 a.m."
            time = "08:00"

        elif end_low < check.time() < end_high:
            date = check + timedelta(days=1)
            if (date.isoweekday() == 7):
                date = check + timedelta(days=1)
                add_speech = "Since its not possible to reserve room now and Sunday, the search was done for next day 8:00 a.m."
            else:
                add_speech = "Since its not possible to reserve room now, the search was done for next day 8:00 a.m."
            time = "08:00"

        elif start_high < check.time() < end_low:
            if (check.isoweekday() == 7):
                date = check + timedelta(days=1)
                add_speech = "Since its not possible to reserve room on Sunday, the search was done for Monday same time."
            else:
                date = check
                add_speech = "default"
            time = datetime.strftime(self.round_time(date), '%H:%M')

        date = datetime.strftime(date, '%Y-%m-%d')
        return date, time, add_speech
Exemple #21
0
def get_weekday(input_date):
    s=input_date.split("-");
    year=int(s[0])
    month=int(s[1])
    day=int(s[2])
    weekdays=[u"周一",u"周二",u"周三",u"周四",u"周五",u"周六",u"周日"]
    return weekdays[date.isoweekday(date(year,month,day))-1]
Exemple #22
0
def get_weekday(input_date):
    s=input_date.split("-");
    year=int(s[0])
    month=int(s[1])
    day=int(s[2])
    weekdays=[u"星期一",u"星期二",u"星期三",u"星期四",u"星期五",u"星期六",u"星期日"]
    return weekdays[date.isoweekday(date(year,month,day))-1]
Exemple #23
0
    def is_active_on(self, date):
        """
        :rtype: bool
        """

        return self.days_relevance[date.isoweekday() % 7] and date not in self.dates_exclusions \
            or date in self.dates_inclusions
    def getPlaceOpeningHoursByDay(self, place, date): #datetime
        # day --> Sunday : 0 || Saturday : 6
        opening_hours = json.loads(place['opening_hours'])
        weekday = date.isoweekday() % 7
        raw_result = opening_hours['day'][weekday]

        result = {}
        result['open'] = -1
        result['close'] = -1

        if raw_result != "Closed":
            str_hours = raw_result.split('-')
            if str_hours[0] == "2400": str_hours[0] = "2359"
            if str_hours[1] == "2400": str_hours[1] = "2359"

            #open
            hours = int(str_hours[0][0:2])
            minutes = int(str_hours[0][2:])
            result['open'] = date.replace(hour=hours, minute=minutes, second=0, microsecond=0)
            #close
            if self.isPlaceNatureType(place) == True:
                hours = 18
                minutes = 30
            else:
                hours = int(str_hours[1][0:2])
                minutes = int(str_hours[1][2:])
            result['close'] = date.replace(hour=hours, minute=minutes, second=0, microsecond=0)

            if result['open'] > result['close']:
                result['close'] += timedelta(days=1)
        return result
Exemple #25
0
def get_fxspot_valuedate(price_date, assetcurrencycountry,
                         pricingcurrencycountry):

    cross_pair = False
    if 'USA' not in [assetcurrencycountry, pricingcurrencycountry]:
        cross_pair = True

    date = price_date
    offset = get_settlement_day_convention(
        countrycode_to_currency(assetcurrencycountry),
        countrycode_to_currency(pricingcurrencycountry))

    if not cross_pair:
        while offset != 0:  # continue to roll date forward until offset becomes 0
            non_businessday_roll = False
            if offset > 1:  # before t+2, only considers non USD currency's holiday
                countries = [
                    assetcurrencycountry if pricingcurrencycountry == 'USA'
                    else pricingcurrencycountry
                ]
                date = date + timedelta(days=1)
                while date.isoweekday() not in range(1, 6) or is_holiday(
                        countries, date):
                    date = date + timedelta(days=1)
                    non_businessday_roll = True
            if offset == 1:  # on t+2, considers both USD and the other currency's holiday
                countries = [assetcurrencycountry, pricingcurrencycountry]
                date = date + timedelta(days=1)
                while date.isoweekday() not in range(1, 6) or is_holiday(
                        countries, date):
                    date = date + timedelta(days=1)
                    non_businessday_roll = True
            offset -= 1
        return date
    else:  # cross pair needs to ensure final settlement date is not US holiday,
        first_currency_vs_USD = get_fxspot_valuedate(price_date,
                                                     assetcurrencycountry,
                                                     'USA')
        second_currency_vs_USD = get_fxspot_valuedate(price_date,
                                                      pricingcurrencycountry,
                                                      'USA')
        date = first_currency_vs_USD if first_currency_vs_USD > second_currency_vs_USD else second_currency_vs_USD
        countries = [assetcurrencycountry, pricingcurrencycountry, 'USA']
        while is_holiday(countries, date) or date.isoweekday() not in range(
                1, 6):
            date = date + timedelta(days=1)
        return date
Exemple #26
0
 def _check_holiday_carryforward(self, holiday_id, start_date, end_date):
     '''
     Checks that there is a public holiday,Saturday and Sunday on date of leave
     @self: Current Record Set
     @api.multi: The decorator of multi
     @param int holiday_id: The current object of id
     @param start_date: Starting date for range
     @param end_date: Ending date for range
     @return: Numbers of day
     -----------------------------------------------------------
     '''
     no_of_day = 0.0
     for holiday_rec in self.browse(holiday_id):
         dates = holiday_rec.get_date_from_range(holiday_rec.date_from,
                                                 holiday_rec.date_to)
         dates = [x.strftime('%Y-%m-%d') for x in dates]
         remove_date = []
         data = []
         contract_ids = self.env['hr.contract'].search([
             ('employee_id', '=', self.employee_id.id),
             ('date_start', '<=', start_date), ('date_end', '>=', end_date)
         ])
         for contract in contract_ids:
             if contract.working_hours and contract.working_hours.attendance_ids:
                 for hol in contract.working_hours.attendance_ids:
                     if hol.dayofweek == '0':
                         data.append(1)
                     if hol.dayofweek == '1':
                         data.append(2)
                     if hol.dayofweek == '2':
                         data.append(3)
                     if hol.dayofweek == '3':
                         data.append(4)
                     if hol.dayofweek == '4':
                         data.append(5)
                     if hol.dayofweek == '5':
                         data.append(6)
                     if hol.dayofweek == '6':
                         data.append(7)
         if contract_ids and contract_ids.ids:
             for day in dates:
                 date = datetime.datetime.strptime(
                     day, DEFAULT_SERVER_DATE_FORMAT).date()
                 if date.isoweekday() not in data:
                     remove_date.append(day)
             for remov in remove_date:
                 if remov in dates:
                     dates.remove(remov)
         public_holiday_ids = self.env['hr.holiday.public'].search([
             ('state', '=', 'validated')
         ])
         for public_holiday_record in public_holiday_ids:
             for holidays in public_holiday_record.holiday_line_ids:
                 if holidays.holiday_date in dates:
                     dates.remove(holidays.holiday_date)
         for day in dates:
             if day >= start_date and day <= end_date:
                 no_of_day += 1
     return no_of_day
Exemple #27
0
    def isHoliday(self, date):
        
        self.logger.debug("Calculating holiday for {}".format(date))
        #split date into components for easy readability in holiday rules below
        w = date.isoweekday() #where Monday is 1 and Sunday is 7
        m = date.month          #Between 1 and 12 inclusive.
        d = date.day    #Between 1 and the number of days in the given month of the given year.
        y = date.year            #Between MINYEAR and MAXYEAR inclusive.
        es = self.EasterSunday(y)
        dayoffset = pd.offsets.Day(1)

        holiday =   (
            # Presidential election days
            (y % 4 == 0 and m == November and d <= 7 and w == Tuesday)
            # New Year's Day (possibly moved to Monday if on Sunday)
            or ((d == 1 or (d == 2 and w == Monday)) and m == January)
            # Washington's birthday (third Monday in February)
            or ((d >= 15 and d <= 21) and w == Monday and m == February)
            # Good Friday
            or (date == es- 2 * dayoffset)
            # Memorial Day (last Monday in May)
            or (d >= 25 and w == Monday and m == May)
            # Independence Day (Monday if Sunday or Friday if Saturday)
            or ((d == 4 or (d == 5 and w == Monday) or
            (d == 3 and w == Friday)) and m == July)
            # Labor Day (first Monday in September)
            or (d <= 7 and w == Monday and m == September)
            # Thanksgiving Day (fourth Thursday in November)
            or ((d >= 22 and d <= 28) and w == Thursday and m == November)
            # Christmas (Monday if Sunday or Friday if Saturday)
            or ((d == 25 or (d == 26 and w == Monday) or
            (d == 24 and w == Friday)) and m == December)
            # Martin Luther King's birthday (third Monday in January)
            or ((d >= 15 and d <= 21) and w == Monday and m == January)
            # President Reagan's funeral
            or (y == 2004 and m == June and d == 11)
            #September 11, 2001
            or (y == 2001 and m == September and (11 <= d and d <= 14))
            # President Ford's funeral
            or (y == 2007 and m == January and d == 2)
            #1977 Blackout
            or (y == 1977 and m == July and d == 14)
            #Funeral of former President Lyndon B. Johnson.
            or (y == 1973 and m == January and d == 25)
            # Funeral of former President Harry S. Truman
            or (y == 1972 and m == December and d == 28)
            # National Day of Participation for the lunar exploration.
            or (y == 1969 and m == July and d == 21)
            # Funeral of former President Eisenhower.
            or (y == 1969 and m == March and d == 31)
            # Closed all day - heavy snow.
            or (y == 1969 and m == February and d == 10)
            # Day after Independence Day.
            or (y == 1968 and m == July and d == 5)
            #June 12-Dec. 31, 1968
            # Four day week (closed on Wednesdays) - Paperwork Crisis
            or (y == 1968 and dd >= 163 and w == Wednesday))

        return holiday
Exemple #28
0
def agregarDia(dfFilt):
    dia = []  #serie donde coloco todo lo que voy a adicionar en la columna
    for index, row in dfFilt.iterrows():
        dia.append(date.isoweekday(dt.strptime(row['Fecha'], '%d/%m/%Y')))
    #https://pandas.pydata.org/pandas-docs/stable/merging.html
    sdia = pd.Series(dia, name='Dia')
    dfFilt = pd.concat([dfFilt, sdia], axis=1)
    return dfFilt
Exemple #29
0
def main():

    # Default returns information from the last week
    config_init()
    mixpanel_main()
    alexa_main()
    klout_main()
    twitter_main()  # Twitter information doesn't change week to week
    github_main()  # Github information doesn't change week to week
    google_analytics_main()
    if (date.isoweekday(date.today()) == 7) or (date.isoweekday(date.today())
                                                == 1):
        client = spreadsheet_auth()
        weekly_ss_recorder(client)
    if (date.today().day == 1):
        client = spreadsheet_auth()
        monthly_ss_recorder(client)
Exemple #30
0
def is_working_day(date, week_days_off=None):
    """Returns True if the date is a working day"""
    if week_days_off is None:
        week_days_off = 6, 7  # default to: saturdays and sundays
    if date is not None:
        if isinstance(date, datetime):
            date = date.date()
        return date.isoweekday() not in week_days_off
Exemple #31
0
def is_working_day(date, week_days_off=None):
    """Returns True if the date is a working day"""
    if week_days_off is None:
        week_days_off = 6, 7  # default to: saturdays and sundays
    if date is not None:
        if isinstance(date, datetime):
            date = date.date()
        return date.isoweekday() not in week_days_off
Exemple #32
0
    def email_notice(self):
        if not (date.isoweekday(datetime.now()) in self.EMAIL_WORKING_DAYS
                and datetime.now().hour in self.EMAIL_WORKING_HOURS):
            return

        try:
            self.send_email()
        except:
            self.logger.error(traceback.format_exc())
Exemple #33
0
    def message_recieved(self, command, message):
        data = {}
        if date.isoweekday(date.today()) == 5:
            data["username"] = "******"
            data["icon_url"] = "http://www.johnstonefitness.com/wp-content/uploads/2011/04/Rebecca-Black-Wallpapers.png"
            data["text"] = "Yes it is friday. We so excited"

        else:
            data["text"] = "No, it is not friday"
        return data
Exemple #34
0
def get_day():
    """
    Returns most recent market day. Does not include Sat/Sunday.
    """
    day = date.today()
    iso_weekday = date.isoweekday(day)
    if iso_weekday == 6:
        day = date.today() - timedelta(days=1)
    elif iso_weekday == 7:
        day = date.today() - timedelta(days=2)
    return day
Exemple #35
0
def weighted_average_sleep_time(user, day_of_the_week):
    app = importlib.import_module(user.app + "." + user.app)
    sleep_times, wake_times = app.sleep_times(user.app_id)
    parsed_times = []
    for sleep_time in sleep_times:
        date = date_for_string(sleep_time)
        if date.isoweekday() == day_of_the_week:
            time = float(date.hour) + float(date.minute) / 60.0
            parsed_times.append(time)

    return stats.weighted_average(parsed_times, lambda x: 1)
Exemple #36
0
def rootadd():
	f_list=g.db.execute("select f_id,f_name,price from fruits").fetchall()
	if request.method=='POST':
		f_name,price=f_list[int(request.form['f_id'])-1][1:]
		setime=request.form['time']
		weekday=date.isoweekday(date(int(setime[0:4]),int(setime[5:7]),int(setime[8:10])))
		no=request.form['tel']+time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
		g.db.execute("insert into orders (id,tel,f_id,numbers,time,re,f_name,price,pay,weekday) values (?,?,?,?,?,?,?,?,?,?)",[no,request.form['tel'],request.form['f_id'],request.form['numbers'],request.form['time'],1,f_name,price,1,weekday])
		g.db.commit()
		flash("添加成功")
	return render_template("rootadd.html",f_list=f_list)
Exemple #37
0
def find_next_vacant(resource, proj, duration=1):
    start_ = proj.start_date()
    next_vacant = []
    j = -1
    while len(next_vacant) < duration:
        j += 1
        if (
            resource.is_vacant(start_ + timedelta(j), start_ + timedelta(j))
            and date.isoweekday(start_ + timedelta(j)) < 6
        ):  # Not weekends:
            next_vacant.append(start_ + timedelta(j))
    return next_vacant[0], next_vacant[-1]
Exemple #38
0
def find_next_vacant_resource(resource):
    start_ = resource[0].tasks[0].start
    next_vacant = []
    j = -1
    while len(next_vacant) < 1:
        j += 1
        if (
            resource[0].is_vacant(start_ + timedelta(j), start_ + timedelta(j))
            and date.isoweekday(start_ + timedelta(j)) < 6
        ):
            next_vacant.append(start_ + timedelta(j))
    return next_vacant[0]
Exemple #39
0
def getDayFromYearMonthAndWeek(aYear, aMonth, aWeekOfMonth, aDayOfWeek):

    day = 1
    dayOfWeek = date.isoweekday(date(aYear, aMonth, day))
    if dayOfWeek == aDayOfWeek:
        day = day + (aWeekOfMonth - 1) * 7
    elif dayOfWeek > aDayOfWeek:
        if aWeekOfMonth == 1:
            raise Exception('Bad input: Week of month is incorrect')
        day = day + 7 - (dayOfWeek - aDayOfWeek) + (aWeekOfMonth - 1) * 7
    elif dayOfWeek < aDayOfWeek:
        day = day + aDayOfWeek - dayOfWeek + (aWeekOfMonth - 1) * 7
    return day
def isbusiday(dt1, dt2):
    DELT_DAY = 4
    delt = (dt2-dt1).days
    count = 0
    mid = dt1
    for i in range(delt):
        mid = mid + timedelta(days=1)
        if date.isoweekday(mid) not in [6,7]:
            count += 1
            if count >= DELT_DAY:
                return True
        else:
            continue
    return False 
Exemple #41
0
def add1():
	w=date.isoweekday(date.today())
	setime=date.today()+timedelta(days=(8-w))
	s=str(setime)
	time=s[:4]+s[5:7]+s[8:]
	no=session['phone']+time
	cur=g.db.execute('select * from fruits order by f_id')
	rowf=cur.fetchall()
	g.db.execute("delete from orders where id=?",[no])
	g.db.commit()
	for i in request.form:
		g.db.execute('insert into orders values(?,?,?,?,1,?,0,?,?)',[no,session['phone'],int(i),int(request.form[i]),s,rowf[int(i)-1][1],rowf[int(i)-1][2]])	
		g.db.commit()
	return redirect(url_for("order"))
Exemple #42
0
 def SnapTask_GetNextRun(self, fs): #===========================
     "TODO"
     self.run('get', '/storage/task/',
                   )
     if 200 != self.status_code:
         raise Exception("Error in SnapTask_GetNextRun fs="+fs +", status=" + str(self.status_code) )
     
     task = (t_item for t_item in self.j if t_item["task_filesystem"] == self.CIFS_getVolName(fs)).next()
     #? is task enabled
     if task["task_enabled"]:
         #? isoweekday(today) in task_byweekday
         if date.isoweekday(date.today()) in [int(s) for s in task["task_byweekday"].split(',')]:
             #? now() BETWEEN (task_begin+N*task_interval AND task_end)
             return task["id"], [snap_t.time() for snap_t in self.SnapTask_dtrange(task) if snap_t.time() > datetime.now().time()][0]
def hourpeak(time_sleep_low_rate, time_sleep_high_rate ):
            c_time=strftime("%H", gmtime())  #This sets the time and integer time to see the rate of download. They are the args that go in hourpeak
            c_time2=int(c_time)
            c_time3=strftime("%H:%M:%S", gmtime())  
            c_date=strftime("%Y-%m-%d",gmtime())
            c_day=date.isoweekday(date.today())

            if ((c_day < 6) and (c_time2 >10 or c_time2 <2)) :
                peak="lowdownload"
            else:
                peak= "highdownload"
            if peak== "lowdownload":   #Function that defines rate of download. I can change the numbers accordinigly 
                time.sleep(time_sleep_low_rate)
            else:
                time.sleep(time_sleep_high_rate)
            print "This is the rate of download", peak
Exemple #44
0
    def SetServices(self, services, filter=False, force=False, hide=False):
        """
        Clears and populates the list data from a `services` dictionary.
        `filter`: When True, the services attributes will be filtered based on
            attributes, e.g. only days matching Sunday will be shown on Sunday.
            Services whose endTime has passed will be grey, but still available
            for selection. Services which are active are marked green and selected
            by default.
        `force`: When true, services whose endTime has passed will be disabled from
            selection.
        `hide`: When true, services whose endTime has passed will not be shown.
        """

        self.items = []
        self.DeleteAllItems()
        self.services = services
        today = date.today()
        now = time.strftime('%H:%M:%S', time.localtime())
        a = 0
        for i in range(len(services)):
            #Filter is True and rough check that times are set for the service.
            if filter:
                if services[i]['day'] == date.isoweekday(today) or services[i]['day'] == 0:
                    #Show if day of week matches today's:
                    self.FormatItem(services[i], a)

                    delta = datetime.datetime.strptime(str(services[i]['endTime']), '%H:%M:%S') - \
                            datetime.datetime.strptime(now, '%H:%M:%S')
                    if delta.days < 0:  #Service has ended
                        self.SetCellTextColour(a, 1, 'grey')
                        if force: self.checkboxes[i].Disable()

                    if services[i]['time'] == '': #Assume All day
                        delta2 = datetime.datetime.strptime('00:00:00', '%H:%M:%S') - datetime.datetime.strptime(now, '%H:%M:%S')
                    else:
                        delta2 = datetime.datetime.strptime(str(services[i]['time']), '%H:%M:%S') - datetime.datetime.strptime(now, '%H:%M:%S')
                    if delta.days == 0 and delta2.days < 0:
                        self.SetCellTextColour(a, 1, 'darkgreen')
                        self.SetToggle(a, True)

                    a += 1 #incrament the list counter
                    self.items.append(services[i]) #List of services that are displayed
                else:
                    pass #Don't add it to the list
            elif not filter:
                self.FormatItem(services[i], a)
                a += 1
	def isValidVideo(self, path):
		_, dateFile, timeFile = path[-1].replace('.avi','').split('_')
		dateTime = self.setTime(dateFile, timeFile)

		startTime1 = self.setTime(dateFile, self.time1_start)
		endTime1 = self.setTime(dateFile, self.time1_end)

		startTime2 = self.setTime(dateFile, self.time2_start)
		endTime2 = self.setTime(dateFile, self.time2_end)

		if date.isoweekday(dateTime) <= 5:
			if (startTime1 <= dateTime <= endTime1) or (startTime2 <= dateTime <= endTime2):
				return True
			else:
				return False
		else:
			return True
Exemple #46
0
    def isHoliday(self, date):
        
        #split date into components fand easy readability in holiday rules below
        w = date.isoweekday() #where Monday is 1 and Sunday is 7
        m = date.month          #Between 1 and 12 inclusive.
        d = date.day    #Between 1 and the number of days in the given month of the given year.
        y = date.year            #Between MINYEAR and MAXYEAR inclusive.
        es = self.EasterSunday(y)
        dayoffset = pd.offsets.Day(1)

        holiday =   (
    
            # New Year's Day
            (d == 1 and m == January)
            # Sao Paulo City Day
            or (d == 25 and m == January)
            # Tiradentes Day
            or (d == 21 and m == April)
            # Labor Day
            or (d == 1 and m == May)
            # Revolution Day
            or (d == 9 and m == July)
            # Independence Day
            or (d == 7 and m == September)
            # Nossa Sra. Aparecida Day
            or (d == 12 and m == October)
            # All Souls Day
            or (d == 2 and m == November)
            # Republic Day
            or (d == 15 and m == November)
            # Black Consciousness Day
            or (d == 20 and m == November and y >= 2007)
            # Christmas
            or (d == 25 and m == December)
            # Passion of Christ
            #TODO: change this
            or (date == es-2 * dayoffset )
            # Carnival
            or (date == es-49 * dayoffset or date == es-48 * dayoffset)
            # Corpus Christi
            or (date== es + 59 * dayoffset)
            # last business day of the year
            or (m == December and (d == 31 or (d >= 29 and w == Friday)))
            )

        return holiday
Exemple #47
0
def get_schoolbus(schoolname):
    cday = date.isoweekday(date.today())
    if cday == 6:
        if schoolname == u"老校区":
            return u"今日老校区发车时间为: 7:50  8:30  9:40  13:20"
        else:
            return u"今日新校区发车时间为: 10:10  11:10  12:00  16:30  17:20"
    elif cday == 7:
        if schoolname == u"老校区":
            return u"今日老校区发车时间为: 8:30"
        else:
            return u"今日新校区发车时间为: 17:20"
    else:
        if schoolname == u"老校区":
            return u"今日老校区发车时间为: 7:50  8:30  9:40  11:00  13:20  15:00  16:00  18:10"
        else:
            return u"今日新校区发车时间为: 7:15  8:10  9:00  10:10  11:10  12:00  14:20  15:40  16:30  17:20  18:30  21:30"
Exemple #48
0
def add1():
	w=date.isoweekday(date.today())
	setime=date.today()+timedelta(days=(8-w))
	s=str(setime)
	time=s[:4]+s[5:7]+s[8:]
	no=session['phone']+time
	cur=g.db.execute('select * from fruits order by f_id')
	rowf=cur.fetchall()
	price=0
	for i in request.form:
		price=price+rowf[int(i)-1][2]*int(request.form[i])
		cur=g.db.execute('select * from orders where tel=? and time=? and f_id=?',[session['phone'],s,int(i)])
		row=cur.fetchall()
		if row==[]:
			g.db.execute('insert into orders values(?,?,?,?,1,?,0)',[no,session['phone'],int(i),int(request.form[i]),s])	
			g.db.commit()
		else:
			g.db.execute('update orders set numbers=?,time=?,re=0 where tel=? and f_id=? and weekday=1 and time=?',[int(request.form[i]),s,session['phone'],int(i),s])	
			g.db.commit()
	return redirect(url_for("order"))
Exemple #49
0
def yummy_day_menu():
    """
    renders daily menu with given template

    example:
        {% yummy_day_menu %}

    :return: context data for inclusion tag decorator
    :rtype: dict
    """
    current_day = date.isoweekday(date.today())
    key = 'yummy_day_menus:%s' % current_day
    menu = cache.get(key)
    if menu is None:
        menu = WeekMenu.objects.get_actual()
        cache.set(key, menu, conf.CACHE_TIMEOUT_LONG)

    return {
        'current_week_day': current_day,
        'current_menu': menu.get(current_day) or {},
        'week_days': conf.WEEK_DAYS,
    }
def checkio(from_date, to_date):
  fd = date.toordinal(from_date)
  td = date.toordinal(to_date)
  count = sum(map(lambda x: date.isoweekday(date.fromordinal(x)) >= 6, 
                  range(fd, td + 1)))
  return count
Exemple #51
0
def get_weekday_today():
    weekdays = [u"星期一", u"星期二", u"星期三", u"星期四", u"星期五", u"星期六", u"星期日"]
    return weekdays[date.isoweekday(date.today()) - 1]
Exemple #52
0
 def isoweekday(self, cr, uid, vals, context=None):
     datas = datetime.strptime(vals["name"],'%Y-%m-%d %H:%M:%S')
     weekday = date.isoweekday(datas)
     return weekday
Exemple #53
0
if a!=[]:
		
	print "Video Found"
#try just with first data-video-id

	id = a[0]['data-video-id']
	webpage2 = urllib2.urlopen('http://www1.narutospot.net/video/play/'+id)
	soup = bs(webpage2)
	string = str(soup.find_all('script')[3].text)
	
	
	url = str(string.split('"')[1])

	

	url = url.strip('\'"')
	print "Video Being Read......"
	video = urllib2.urlopen(url).read()

	print "Video Read" 
	filename = "naruto-"+str(video_to_download)+".mp4" 
	with open(filename,'wb') as f:
		f.write(video)
	print "Video Saved naruto.mp4"
	with open('naruto.txt','w') as f:
		f.write(str(video_to_download))
else:
	print "Video not released"
	with open('error.txt','a') as f:
		f.write("Naruto "+ str(video_to_download)+" not released yet. "+str(date.isoweekday(date.today())))
Exemple #54
0
def get_weekday(file):
  date = __get_date(file)
  try:
    return str(date.isoweekday()).split()[0]
  except:
    return str(date.day_of_week).split()[0]