def view_team(project_id, sprint_id): response = requests.get(app.config['SCRUM_API'] + '/get/project/{0}'.format(project_id, sprint_id)) project_data = response.json() response = requests.get(app.config['SCRUM_API'] + '/get/project/{0}/{1}'.format(project_id, sprint_id)) sprint_data = response.json() response = requests.get(app.config['SCRUM_API'] + '/get/daytypes/{0}'.format(project_id)) daytype_data = response.json() weekend = set([5, 6]) sprint_days = [] day = 0 for i in range(1, (int(sprint_data['sprint_days'])) +1): date = datetime.strptime(sprint_data['start_date'], '%Y-%m-%d') + timedelta(days=day) if date.weekday() in weekend: day += 1 date = datetime.strptime(sprint_data['start_date'], '%Y-%m-%d') + timedelta(days=day) if date.weekday() in weekend: day += 1 date = datetime.strptime(sprint_data['start_date'], '%Y-%m-%d') + timedelta(days=day) day = day + 1 #print(day) sprint_days.append(date.strftime("%a")) return render_template('team.html', sprint_data=sprint_data, project_data=project_data, sprint_days=sprint_days, daytype_data=daytype_data)
def getContributors(): # got bugs. let's get contributors! try: allcontributors = json.load(open("/var/local/bz-triage/contributors.cfg")) except: logging.info("Failed to open contributors file.....") print("Failed to open contributors.cfg.") exit(-1) #print str(allcontributors) # Assign bugs to contributors. The process below favors getting # some bugs to many people over getting many bugs to some people. today = list() for contrib in allcontributors: if contrib[3] == "daily" \ or (contrib[3] == "workdays" and date.weekday(date.today()) < 5) \ or (contrib[3] == "weekly" and date.weekday(date.today()) == 0 ): today.append(contrib) return today;
def meetup_day(year, month, day, position): pos = checkInputs(year, month, day, position) if ( pos != None ): referenceDate = date(year, month, 1) count = 0 referenceDay = date.weekday(referenceDate) while ( days[referenceDay].upper() != day.upper() ): referenceDate = referenceDate + timedelta(days=1) referenceDay = date.weekday(referenceDate) # Now we've reached the first day of the month corresponding to our input ('Monday', 'Tuesday', etc...) if ( pos == 'teenth' ): while ( referenceDate.day < 13 ): referenceDate = referenceDate + timedelta(days=7) else: count = 1 if ( pos == 'last' ): # For the 'last' position, it's easiest to begin from first day of next month # and go backwards from there referenceDate = date(year, month + 1, 1) while ( days[referenceDate.weekday()] != day ): referenceDate = referenceDate - timedelta(days=1) return referenceDate while ( count != int(pos) ): referenceDate = referenceDate + timedelta(days=7) if ( referenceDate.month != month ): raise MeetupDayException("This day does not exist!") count = count + 1 return referenceDate else: raise MeetupDayException("Wrong day value")
def week_days(date=date.today()): if date.weekday() > 0: date= date - timedelta(days=date.weekday()) days=list() for i in range(6): days.append(date) date = date + timedelta(days=1) days.append(date) return days
def estDansLaSemaineTravail(dateStr, dateRef) : try : date = datetime.datetime.strptime(dateStr,'%d/%m/%Y %H:%M') except : return False if(date.weekday() == 5 or date.weekday() == 6): return False if (date == None): return False return dateRef - SEMAINE <= date and date < dateRef
def getDayStr(): days = {0: 'Maanantai', 1: 'Tiistai', 2: 'Keskiviikko', 3: 'Torstai', 4: 'Perjantai', 5: 'Lauantai'} day = date.today() if date.weekday(day) not in days: return day_name = days[date.weekday(day)] dayStr = '%s %i.%i' % (day_name, day.day, day.month) return dayStr
def is_trade_date(date): if date.weekday() == 5 or date.weekday() == 6: return False # Saturday or Sunday datestr = date.strftime('%Y-%m-%d') #print datestr if datestr in legalholidays.legal_holidays: #print 'False' return False if date.year < 2015 or date.year > 2018: raise Exception('year not supported!') return True
def getDayStr(): days = {0: "Maanantai", 1: "Tiistai", 2: "Keskiviikko", 3: "Torstai", 4: "Perjantai"} day = date.today() if date.weekday(day) not in days: return day_name = days[date.weekday(day)] dayStr = "%s %i.%i" % (day_name, day.day, day.month) return dayStr
def get_date_for_last_gambling(): date = today() time = now() any_gambling_today = GamblingConfiguration.objects.filter(days_of_week__contains=date.weekday(), time__lt=time) if any_gambling_today: return date else: if date.weekday() == 0: return date - timedelta(2) else: return date - timedelta(1)
def from_date(cls, date, period=None): """ Create a day long daterange from for the given date. >>> daterange.from_date(date(2000, 1, 1)) daterange([datetime.date(2000, 1, 1),datetime.date(2000, 1, 2))) :param date: A date to convert. :param period: The period to normalize date to. A period may be one of: ``day`` (default), ``week``, ``american_week``, ``month``, ``quarter`` or ``year``. :return: A new range that contains the given date. .. seealso:: There are convenience methods for most period types: :meth:`~spans.types.daterange.from_week`, :meth:`~spans.types.daterange.from_month`, :meth:`~spans.types.daterange.from_quarter` and :meth:`~spans.types.daterange.from_year`. :class:`~spans.types.PeriodRange` has the same interface but is period aware. This means it is possible to get things like next week or month. .. versionchanged:: 0.4.0 Added the period parameter. """ if period is None or period == "day": return cls(date, date, upper_inc=True) elif period == "week": start = date - timedelta(date.weekday()) return cls(start, start + timedelta(7)) elif period == "american_week": start = date - timedelta((date.weekday() + 1) % 7) return cls(start, start + timedelta(7)) elif period == "month": start = date.replace(day=1) return cls(start, (start + timedelta(31)).replace(day=1)) elif period == "quarter": start = date.replace(month=(date.month - 1) // 3 * 3 + 1, day=1) return cls(start, (start + timedelta(93)).replace(day=1)) elif period == "year": start = date.replace(month=1, day=1) return cls(start, (start + timedelta(366)).replace(day=1)) else: raise ValueError("Unexpected period, got {!r}".format(period))
def format_week(self, char, num): if char.islower(): # week of year day_of_year = self.get_day_of_year() week = self.get_week_number(day_of_year) if week == 0: date = self.value - timedelta(days=day_of_year) week = self.get_week_number(self.get_day_of_year(date), date.weekday()) return self.format(week, num) else: # week of month week = self.get_week_number(self.value.day) if week == 0: date = self.value - timedelta(days=self.value.day) week = self.get_week_number(date.day, date.weekday()) return '%d' % week
def vacuum(day_index=date.weekday(datetime.now()), database=None, table_config={}, dryrun=False): # ugh global _DBNAME global _TABLE_CONFIG _DBNAME = database _TABLE_CONFIG = table_config tables_to_vac = [] report("vacuum for day index %s against database %s" % (day_index, database)) for days, tables_for_day in table_config.iteritems(): if not hasattr(days, "__iter__"): days = [days] if day_index in days: for item in tables_for_day: if callable(item): tables_to_vac.extend(item()) else: tables_to_vac.append(item) tables_to_vac = dedupe(tables_to_vac) report("vacuum queue is %s" % tables_to_vac) for table in tables_to_vac: if table is not None and dryrun is not True: vacuum_table(database, table, dryrun)
def _get_maintenance_activity_group_by_date(date, rank): week = date - timedelta(date.weekday()) groups = Maintenance_Activity_Group.get_maintenance_activity_groups(week) if groups: if len(rank) == 5: # fixed maintenance. rank = 'HH:MM' try: dt = date.replace(hour = int(rank[0:2]), minute = int(rank[3:5])) except ValueError: # badly formatted time, should be "HH:MM" print "_get_maintenance_activity_group_by_date(", date, ",", rank, "); in resource_cal.py:" print "ValueError: badly formatted time, should be 'HH:MM'" return None # cant make anything of this, return None. def comp_mag(mag): return mag.get_start(tzname = 'ET') == dt elif len(rank) == 1 and rank.isalpha(): # floating maintenance: rank = 'A', 'B', etc. def comp_mag(mag): return TimeAgent.truncateDt(mag.get_start(tzname = 'ET')) == date and mag.rank.upper() == rank.upper() else: # whoops! rank should be either '[A-Z]' or 'HH:MM' print "_get_maintenance_activity_group_by_date(", date, ",", rank, "); in resource_cal.py:" print "poorly formated rank; must be either '[A-Z]' or 'HH:MM'." return None groups = filter(comp_mag, groups) return groups[0] if groups else None return None
def main(): #DATE OBJECTS #Get today's date from the simple today() method from the date class today = date.today() print "Today's date is ", today #print out the date's individual components print "Date Components: ", today.day, today.month, today.year #retrieve today's weekday (0=Monday, 6=Sunday) print "Today's Weekday #: ", today.weekday() print " " #DATETIME OBJECTS #Get today's date from the datetime class today1 = datetime.now() print "The current date and time is ", today1 #Get the current time t = datetime.time(today1) print "The current time is ",t #weekday returns 0 (monday) through 6(sunday) wd = date.weekday(today1) #Days start from 0 for Monday days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] print "Today is day number %d" % wd print "Which is a " + days[wd]
def _checkParams(self): RHDisplayCategoryBase._checkParams(self) self.detail = request.args.get("detail", "event") if self.detail not in ("event", "session", "contribution"): raise BadRequest("Invalid detail argument") self.period = request.args.get("period", "day") if self.period not in ("day", "month", "week"): raise BadRequest("Invalid period argument") if "date" in request.args: try: date = datetime.strptime(request.args["date"], "%Y-%m-%d") except ValueError: raise BadRequest("Invalid date argument") else: date = datetime.now() date = self.category.display_tzinfo.localize(date) date = date.replace(hour=0, minute=0, second=0, microsecond=0) if self.period == "day": self.start_dt = date self.end_dt = self.start_dt + relativedelta(days=1) elif self.period == "week": self.start_dt = date - relativedelta(days=date.weekday()) self.end_dt = self.start_dt + relativedelta(days=7) elif self.period == "month": self.start_dt = date + relativedelta(day=1) self.end_dt = self.start_dt + relativedelta(months=1)
def processResult(raw): event_name = ' '.join(raw['actions']) event_description = raw['description'] event_privacy = True if raw['privacy'] == 'public' else False today = date.weekday(date.today()) result = {} result['event_name'] = event_name result['event_description'] = event_description result['event_privacy'] = event_privacy result['dates'] = [] for i in xrange(len(raw['times'])): tempResult = [] tempStartTime = parseTime(raw['times'][i][0]) tempEndTime = parseTime(raw['times'][i][1]) tempDay = raw['days'][i] tempReoccurring = raw['reoccurings'][i] tempDate = timezone.now() if tempReoccurring == 'this': increment = dayWeekToIndex(tempDay) - today tempResult.append(False) # event not reoccuring elif tempReoccurring == 'next': increment = dayWeekToIndex(tempDay) - today + 7 tempResult.append(False) # event not reoccuring else: increment = dayWeekToIndex(tempDay) - today tempResult.append(True) # event not reoccuring tempDate += timedelta(days=increment) tempStartDate = tempDate.replace(hour=tempStartTime, minute=0, second=0) tempEndDate = tempDate.replace(hour=tempEndTime, minute=0, second=0) tempResult.append(tempStartDate) tempResult.append(tempEndDate) result['dates'].append(tempResult) return result
def checkDate(day): parts = day.split('_') month = int(parts[0]) day = int(parts[1]) year = int(parts[2]) oldDate = date(year, month, day) return date.weekday(oldDate)
def migrateOilQuotesFromFile(filename): f = open(filename) reader = csv.reader(f) curs_date = '01.01.2015' count_migrate_qoutes = 0 quote_type = 'brent' for row_index, row in enumerate(reader): if curs_date != row[0].split(';')[0]: if row[0].split(';')[1] == '17:00:00': quote_date = datetime.strptime(row[0].split(';')[0], "%d.%m.%Y") try: q = Quote.objects.get(quote_date=quote_date, quote_type=quote_type) except Quote.DoesNotExist: print "Quote on date" + str(quote_date) + "doesn't exist" if date.weekday(quote_date) == 4: q_sat = Quote(quote_value=round(float(row[0].split(';')[5]), 4), quote_type=quote_type, quote_date=quote_date+timedelta(days=1)) q_sat.save() q_sun = Quote(quote_value=round(float(row[0].split(';')[5]), 4), quote_type=quote_type, quote_date=quote_date+timedelta(days=2)) q_sun.save() q = Quote(quote_value=round(float(row[0].split(';')[5]), 4), quote_type=quote_type, quote_date=quote_date) q.save() count_migrate_qoutes += 1 return count_migrate_qoutes
def _checkParams(self): RHDisplayCategoryBase._checkParams(self) self.detail = request.args.get('detail', 'event') if self.detail not in ('event', 'session', 'contribution'): raise BadRequest('Invalid detail argument') self.period = request.args.get('period', 'day') if self.period not in ('day', 'month', 'week'): raise BadRequest('Invalid period argument') if 'date' in request.args: try: date = datetime.strptime(request.args['date'], '%Y-%m-%d') except ValueError: raise BadRequest('Invalid date argument') else: date = datetime.now() date = self.category.display_tzinfo.localize(date) date = date.replace(hour=0, minute=0, second=0, microsecond=0) if self.period == 'day': self.start_dt = date self.end_dt = self.start_dt + relativedelta(days=1) elif self.period == 'week': self.start_dt = date - relativedelta(days=date.weekday()) self.end_dt = self.start_dt + relativedelta(days=7) elif self.period == 'month': self.start_dt = date + relativedelta(day=1) self.end_dt = self.start_dt + relativedelta(months=1)
def test_day(self, daterules): inputrules = daterules.find("*") date = self.evaluate_daterules(inputrules) day = daterules.get("day") actual_weekday = date.weekday() test_weekday = Library.weekday_index(day) return actual_weekday == test_weekday
def main(): ## DATE OBJECTS # Get today's date from the simple today() method from the date class # today = date.today() # print "Today's date is ", today # # print out the date's individual components # print "Date Components: ", today.day, today.month, today.year # # retrieve today's weekday (0=Monday, 6=Sunday) # print "Today's Weekday #: ", today.weekday() ## DATETIME OBJECTS # Get today's date from the datetime class today = datetime.now() # print "The current date and time is ", today; # # Get the current time # t = datetime.time(datetime.now()) # print "The current time is ", t # weekday returns 0 (monday) through 6 (sunday) wd = date.weekday(today) # Days start at 0 for Monday days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"] print "Today is day number %d" % wd print "Which is a " + days[wd]
def list_daily(soup, day): from datetime import date day_selector = { 0: 'mon', 1: 'tue', 2: 'wed', 3: 'thu', 4: 'fri', 5: 'sat', 6: 'sat' }.get(date.weekday(date.today()) if not day else day[0] - 1, None) # 0 stands for monday in time module if not day_selector: print("Nothing found.") return content = soup.select(".listWrap li") content = filter(lambda x:x["data-week"] == day_selector, content) # prepare report text table = [(u"Status", u"ID", u"Name")] for li in content: status = u"Update" if "newChecked" in li["class"] else u"Normal" table.append((status, li["id"], li.find("h4").get_text())) # prettify table text = prettify_table(table) print(text.encode("gb18030")) print("\n{0} bangumi counted.".format(len(table) - 1))
def getTimeRemainingToday(self): #get the total Min left that i need to work today #get the day of the week weekDay = date.weekday(datetime.now()) #subtract the amount of hours needed for an 8 hr workday, depending on what day of the week it is, to calculate how many hours need to be worked today. # if weekDay == 0: # remaning = (8 * 60) - int(self.currentWorked) # elif weekDay == 1: # remaning = (16 * 60) - int(self.currentWorked) # elif weekDay == 2: # remaning = (24 * 60) - int(self.currentWorked) # elif weekDay == 3: # remaning = (32 * 60) - int(self.currentWorked) # elif weekDay == 4: # remaning = (40 * 60) - int(self.currentWorked) # else: # remaining = 0 # print ('Why are you working on a weekend?') hrsToSubtract = { 0 : (8 * 60) - int(self.currentWorked), 1 : (16 * 60) - int(self.currentWorked), 2 : (24 * 60) - int(self.currentWorked), 3 : (32 * 60) - int(self.currentWorked), 4 : (40 * 60) - int(self.currentWorked) } remaning = hrsToSubtract[weekDay] # see if I had a lunch break(before noon), if not, add 30 min to remaining time now = datetime.now() noon = now.replace(hour=12, minute=0, second=0, microsecond=0) if now < noon: remaning = remaning + 30 return timedelta(minutes= remaning)
def getMediaData(self, weekList, url): data = wgetUrl(url) # If zero, an error occurred retrieving the url, throw an error if len(data) == 0: self.mediaProblemPopup() short = '' name = '' date1 = '' stream = '' channel = '' icon = '' links = (re.compile ('<entry>\n <title type="text">(.+?)</title>\n <id>tag:feeds.bbc.co.uk,2008:PIPS:(.+?)</id>\n <updated>(.+?)</updated>\n <content type="html">\n <p>\n <a href=".+?">\n <img src="(.+?)" alt=".+?" />\n </a>\n </p>\n <p>\n (.+?)\n </p>\n </content>').findall(data)) for line in links: name = checkUnicode(line[0]) stream = line[1] # Format the date to display onscreen year = int(line[2][0:4]) month = int(line[2][5:7]) day = int(line[2][8:10]) oldDate = date(int(year), int(month), int(day)) # year, month, day dayofWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] date1 = dayofWeek[date.weekday(oldDate)] + " " + oldDate.strftime("%d %b %Y") + " " +line[2][11:16] icon = line[3] icon_type = '.jpg' short = checkUnicode(line[4]) channel = "" weekList.append((date1, name, short, channel, stream, icon, icon_type, False))
def show_graph_steps(self): new_evdlist = list() #print "", Weekday[self.getDayOfWeek("11/12/1970")] evdlist = self.personis_um.get_evidence_new(context=['Devices','Fitbit','Activity'], componentid="steps") import datetime prev_date = date(2000,1,1) i = 0 newval = 0 weekday_data = [0,0,0,0,0,0,0] for ev in evdlist: print datetime.datetime.fromtimestamp(int(ev.time)).strftime('%Y-%m-%d'), ev.value try: um_time = ev.time import datetime tt = time.localtime(int(um_time)) track_date = date(tt[0],tt[1],tt[2]) #datetime.datetime.fromtimestamp(int(time)).strftime('%Y-%m-%d') if prev_date != track_date: if newval != 0: new_evdlist.append(int(newval)) print "Fitbit data on %s is %s"%(str(prev_date), newval) weekday_data[date.weekday(prev_date)] += newval newval = int(ev.value) prev_date = track_date else: newval += int(ev.value) except Exception,e: print e return "Error: "+str(e)
def main(): ## Date objects # Get todays date from simple today() method in date class today = date.today() print "\nToday's date is ", today # print out the date's indivual components print "\nToday's day is ", today.day print "\nToday's month is ", today.month print "\nToday's year is ", today. year # retrieve today's weekday number print "\nToday's weekday # is ", today.weekday() # NOW USE DATETIME TO GET TIMES today_time = datetime.now() print "\nThe current date and time is ", today_time #Get current time t = datetime.time(datetime.now()) print "\nThe current time is ", t # weekday return the number of the weekday wd = date.weekday(date.today()) # once you have the number use that index to access the correct word from the following list days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunda"] print "\nToday is day number %d" % wd print "which is a ", days[wd]
def make_date(self): date = self.date if self.time == 'After': date = date + timedelta(days=1) while date.weekday()>=5: date = date + timedelta(days=1) self.date = date
def main(): ## DATE OBJECTS # Get today's date from the simple today() method from the date class today = date.today() print "Today's date is", today #print out the date's individual components print "Date components: ", today.day, today.month, today.year # retrieve today's weekday (0=Monday, 6=Sunday) print "Today's weekday #: ", today.weekday() print " " # DATETIME OBJECTS # Get today's date from datetime class today = datetime.now() print "The current date & time is : ", today #Get the current time t = datetime.time(datetime.now()) print "The current time is :", t #weekday return 0 (Monday) through 6 (Sunday) wd = date.weekday(today) # Days starts at 0 for Monday days = ["monday", "tuesday", "wedneday", "thursday", "friday", "saturday", "sunday"] print "Today is day number ", wd print "Which is a " + days[wd] print " "
def forecast(weather_data): """ main function to create display data in the form of a list, each day is 1 entry in the list. First an integer value for the current date is set, then a string is started with that day followed by the high and low temps, followed by the conditions. Upon each iteration of the loop the high, low, and day is incremented as necessary, the condition is pulled from the appropriate part of the JSON response from openweathermap.org's API and the string for each day is constructed in its entirety before it is appended to the final list. :param weather_data: :return: display data for the week """ current_day = date.weekday(datetime.today()) # returns an integer for today's day: Mon == 0 and Sun == 6 days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] display = [] high = high_temp(weather_data) low = low_temp(weather_data) x = 0 while x < 7: display_string = """{d}'s high is {h} with a low of {l}, you should expect {c}""".format(d=days[current_day], h=high[x], l=low[x], c=weather_data[u'list'][x][u'weather'][0][u'description']) display.append(display_string) x += 1 current_day += 1 if current_day > 6: current_day = 0 return display
def main(): today = date.today() print "Today is ", today print " " print "Date Components: ", today.day, today.month, today.year print " " print "Today is weekday #: ", today.weekday() print " " today = datetime.now() print "The current date and time is: ", today; print " " t = datetime.time(datetime.now()) print "The current time is: ", t print " " wd = date.weekday(today) print " " days = ["Mon", "Tue", "Wed", "Thurs", "Fri", "Sat", "Sun"] #print "Today is day number %d" % wd #print "which is a " + days[wd] print "Today is " + days[wd] + " which is the %d day of the week if we make Sunday day number 0" % wd print " " print "And now we'll do some datetime formatting :) " print " " now = datetime.now() print now.strftime("%Y") print " " print now.strftime("%a, %d %B, %Y") print " " print now.strftime("%c") print now.strftime("%x") print now.strftime("%X") print " " print now.strftime("%I:%M:%S %p") print now.strftime("%H:%M")
def onchange_date_range(self): if self.date_range: date = datetime.today() if self.date_range == 'today': self.date_from = date.strftime("%Y-%m-%d") self.date_to = date.strftime("%Y-%m-%d") if self.date_range == 'this_week': day_today = date - timedelta(days=date.weekday()) self.date_from = ( day_today - timedelta(days=date.weekday())).strftime("%Y-%m-%d") self.date_to = (day_today + timedelta(days=6)).strftime("%Y-%m-%d") if self.date_range == 'this_month': self.date_from = datetime(date.year, date.month, 1).strftime("%Y-%m-%d") self.date_to = datetime( date.year, date.month, calendar.mdays[date.month]).strftime("%Y-%m-%d") if self.date_range == 'this_quarter': if int((date.month - 1) / 3) == 0: # First quarter self.date_from = datetime(date.year, 1, 1).strftime("%Y-%m-%d") self.date_to = datetime( date.year, 3, calendar.mdays[3]).strftime("%Y-%m-%d") if int((date.month - 1) / 3) == 1: # Second quarter self.date_from = datetime(date.year, 4, 1).strftime("%Y-%m-%d") self.date_to = datetime( date.year, 6, calendar.mdays[6]).strftime("%Y-%m-%d") if int((date.month - 1) / 3) == 2: # Third quarter self.date_from = datetime(date.year, 7, 1).strftime("%Y-%m-%d") self.date_to = datetime( date.year, 9, calendar.mdays[9]).strftime("%Y-%m-%d") if int((date.month - 1) / 3) == 3: # Fourth quarter self.date_from = datetime(date.year, 10, 1).strftime("%Y-%m-%d") self.date_to = datetime( date.year, 12, calendar.mdays[12]).strftime("%Y-%m-%d") if self.date_range == 'this_financial_year': if self.financial_year == 'january_december': self.date_from = datetime(date.year, 1, 1).strftime("%Y-%m-%d") self.date_to = datetime(date.year, 12, 31).strftime("%Y-%m-%d") if self.financial_year == 'april_march': if date.month < 4: self.date_from = datetime(date.year - 1, 4, 1).strftime("%Y-%m-%d") self.date_to = datetime(date.year, 3, 31).strftime("%Y-%m-%d") else: self.date_from = datetime(date.year, 4, 1).strftime("%Y-%m-%d") self.date_to = datetime(date.year + 1, 3, 31).strftime("%Y-%m-%d") if self.financial_year == 'july_june': if date.month < 7: self.date_from = datetime(date.year - 1, 7, 1).strftime("%Y-%m-%d") self.date_to = datetime(date.year, 6, 30).strftime("%Y-%m-%d") else: self.date_from = datetime(date.year, 7, 1).strftime("%Y-%m-%d") self.date_to = datetime(date.year + 1, 6, 30).strftime("%Y-%m-%d") date = (datetime.now() - relativedelta(days=1)) if self.date_range == 'yesterday': self.date_from = date.strftime("%Y-%m-%d") self.date_to = date.strftime("%Y-%m-%d") date = (datetime.now() - relativedelta(days=7)) if self.date_range == 'last_week': day_today = date - timedelta(days=date.weekday()) self.date_from = ( day_today - timedelta(days=date.weekday())).strftime("%Y-%m-%d") self.date_to = (day_today + timedelta(days=6)).strftime("%Y-%m-%d") date = (datetime.now() - relativedelta(months=1)) if self.date_range == 'last_month': self.date_from = datetime(date.year, date.month, 1).strftime("%Y-%m-%d") self.date_to = datetime( date.year, date.month, calendar.mdays[date.month]).strftime("%Y-%m-%d") date = (datetime.now() - relativedelta(months=3)) if self.date_range == 'last_quarter': if int((date.month - 1) / 3) == 0: # First quarter self.date_from = datetime(date.year, 1, 1).strftime("%Y-%m-%d") self.date_to = datetime( date.year, 3, calendar.mdays[3]).strftime("%Y-%m-%d") if int((date.month - 1) / 3) == 1: # Second quarter self.date_from = datetime(date.year, 4, 1).strftime("%Y-%m-%d") self.date_to = datetime( date.year, 6, calendar.mdays[6]).strftime("%Y-%m-%d") if int((date.month - 1) / 3) == 2: # Third quarter self.date_from = datetime(date.year, 7, 1).strftime("%Y-%m-%d") self.date_to = datetime( date.year, 9, calendar.mdays[9]).strftime("%Y-%m-%d") if int((date.month - 1) / 3) == 3: # Fourth quarter self.date_from = datetime(date.year, 10, 1).strftime("%Y-%m-%d") self.date_to = datetime( date.year, 12, calendar.mdays[12]).strftime("%Y-%m-%d") date = (datetime.now() - relativedelta(years=1)) if self.date_range == 'last_financial_year': if self.financial_year == 'january_december': self.date_from = datetime(date.year, 1, 1).strftime("%Y-%m-%d") self.date_to = datetime(date.year, 12, 31).strftime("%Y-%m-%d") if self.financial_year == 'april_march': if date.month < 4: self.date_from = datetime(date.year - 1, 4, 1).strftime("%Y-%m-%d") self.date_to = datetime(date.year, 3, 31).strftime("%Y-%m-%d") else: self.date_from = datetime(date.year, 4, 1).strftime("%Y-%m-%d") self.date_to = datetime(date.year + 1, 3, 31).strftime("%Y-%m-%d") if self.financial_year == 'july_june': if date.month < 7: self.date_from = datetime(date.year - 1, 7, 1).strftime("%Y-%m-%d") self.date_to = datetime(date.year, 6, 30).strftime("%Y-%m-%d") else: self.date_from = datetime(date.year, 7, 1).strftime("%Y-%m-%d") self.date_to = datetime(date.year + 1, 6, 30).strftime("%Y-%m-%d")
def findDay(date): born = date.weekday() return (calendar.day_name[born])
def elevatorDay(date): return date.month == 7 and date.weekday() == 4 and date.day in range( 25, 32)
apr07_2018_path, may05_2018_mta_data, jun02_2018_mta_data, jul07_2018_mta_data, aug04_2018_mta_data, sep01_2018_mta_data, oct06_2018_mta_data, nov03_2018_mta_data, dec01_2018_mta_data] ####### SAMPLE DATASET ### looking at the most recent MTA data from June 29, 2019 in NY path = "http://web.mta.info/developers/data/nyct/turnstile/turnstile_190629.txt" new_cols = ["C/A", "UNIT", "SCP", "STATION", "LINENAME", "DIVISION", "DATE", "TIME", "DESC", "ENTRIES", "EXITS"] MTA_data = pd.read_csv(path, sep=",", header=0, names=new_cols) ### add turnstile passes column MTA_data['TURNSTILE_PASSES'] = MTA_data['ENTRIES'] + MTA_data['EXITS'] MTA_data.sample(10) ## add day of the week column MTA_data["DATE"] = pd.to_datetime(MTA_data["DATE"]) days = [calendar.day_name[date.weekday()] for date in MTA_data["DATE"]] MTA_data["DAY_OF_WEEK"] = days ### sort and group by date MTA_data["DATE"] = MTA_data["DATE"] date_grouped_MTA_data = MTA_data.groupby("DATE").count() date_sorted_MTA_data = MTA_data.sort_values("DATE") # rearrange columns cols = MTA_data.columns.tolist() len(cols) c1, c2, c3 = list(cols[:7]), cols[-1:], list(cols[7:-1]) cols = c1 + c2 + c3 cols MTA_data = MTA_data[cols] # new DataFrame with relevant data
def is_workday(date): if not isinstance(date, datetime.date): return "date must be time type" elif date.weekday() == 5 or date.weekday() == 6: return False return True
def get(self, request, **kargs): profissional = kargs['profissional'] validar_profissional(profissional) self.context['profissional'] = profissional hoje = datetime.now().date() if 'mes' and 'ano' in kargs: validar_data(f"01-{kargs['mes']}-{kargs['ano']}") mes = int(kargs['mes']) ano = int(kargs['ano']) else: mes = hoje.month ano = hoje.year meses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'] self.context['mes'] = meses[mes - 1] self.context['ano'] = ano data_inicio = date(ano, mes, 1) data_fim = date(ano, mes + 1, 1) if mes != 12 else date(ano + 1, 1, 1) agendamentos = list(Agendamento.objetos.filter(profissional=profissional, data__gte=data_inicio, data__lt=data_fim).values_list('data', 'turno')) feriados = list(Feriado.objetos.filter(data__gte=data_inicio, data__lt=data_fim).values_list('data', flat=True)) dias_indisponiveis = list( DiaIndisponivel.objetos.filter(data__gte=data_inicio, data__lt=data_fim).values_list('data', flat=True)) incremento = timedelta(1) final = (data_fim - incremento).day self.context['anterior'] = {'mes': (data_inicio - incremento).strftime('%m'), 'ano': (data_inicio - incremento).strftime('%Y')} self.context['proximo'] = {'mes': data_fim.strftime('%m'), 'ano': data_fim.strftime('%Y')} dias = [] primeiro_dia = date.weekday(data_inicio) if primeiro_dia != 6: semana = (primeiro_dia + 1) * [{'data': '', 'status': 'desabilitado', 'motivo': 'mes'}] else: semana = [] data = data_inicio contador = primeiro_dia for i in range(final): agend_manha = agendamentos.count((data, 'M')) agend_tarde = agendamentos.count((data, 'T')) data_formatada = data.strftime('%d-%m-%Y') if contador % 7 == 5: semana.append({'data': data_formatada, 'status': 'desabilitado', 'motivo': 'sábado'}) dias.append(semana) semana = [] elif contador % 7 == 6: semana.append({'data': data_formatada, 'status': 'desabilitado', 'motivo': 'domingo'}) elif data in feriados: semana.append({'data': data_formatada, 'status': 'desabilitado', 'motivo': 'feriado'}) elif data in dias_indisponiveis: semana.append({'data': data_formatada, 'status': 'desabilitado', 'motivo': 'indisponível'}) elif data < hoje: semana.append({'data': data_formatada, 'status': 'desabilitado'}) else: semana.append({'data': data_formatada, 'status': 'disponivel', 'motivo': {'manha': agend_manha, 'tarde': agend_tarde}}) if i == final - 1 and contador % 7 != 5: dias.append(semana) data += incremento contador += 1 self.context['calendario'] = dias return render(request, 'agendamento/calendario.html', self.context)
def get_weekspan(date): weeklist_begin = date - timedelta(days=date.weekday()) weeklist_end = weeklist_begin + timedelta(days=7) return weeklist_begin, weeklist_end
def is_weekend(self, date: date) -> bool: return date.weekday() in [WeekDays.Sunday, WeekDays.Saturday]
#Question 1 from datetime import date days = [ 'Monday', 'Tuesday', 'Wednessday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] print(days[date.weekday(date.today())]) #Question 2 import webbrowser webbrowser.open('https://www.youtube.com/watch?v=DUMb9fxWrN4') #Question 3 import os os.rename('file.txt', 'file.jpg')
def isthursday(self, datestr): """判断是否为星期4""" if date.weekday(self.toDate(datestr)) == 3: return True else: return False
def main(): '''dates and holidays''' days = [ 'Mondas', 'Tirdas', 'Middas', 'Turdas', 'Fredas', 'Loredas', 'Sundas' ] months = [ 'placeholder', #not accessed 'Morning Star', 'Sun\'s Dawn', 'First Seed', 'Rain\'s Hand', 'Second Seed', 'Midyear', 'Sun\'s Height', 'Last Seed', 'Hearthfire', 'Frostfall', 'Sun\'s Dusk', 'Evening Star' ] today = datetime.now() weekday = date.weekday(today) day = today.day month = today.month print('the date is', day, 'of', months[month]) print('of the week it is', days[weekday]) if day == '1' and month == 'Morning Star': print('today is the New Life Festival!') elif day == '15' and month == 'Morning Star': print('today is South Wind\'s Prayer!') elif day == '16' and month == 'Morning Star': print('today is the Festival of Lights!') elif day == '13' and month == 'Sun\'s Dawn': print('today is the Feast of the Dead!') elif day == '16' and month == 'Sun\'s Dawn': print('today is Hearts Day!') elif day == ' 7' and month == 'Second Seed': print('today is the First Planting!') elif day == '28' and month == 'Rain\'s Hand': print('today is Jester\'s Day!') elif day == '2' and month == 'Second Seed': print('today is the Second Planting!') elif day == '16' and month == 'Midyear': print('todat is the Mid Year Celebration!') elif day == '10' and month == 'Sun\'s Height': print('today is the Merchant\'s Festival') elif day == '20' and month == 'Sun\'s Height': print('today is Sun\'s Rest!') elif day == '27' and month == 'Last Seed': print('today is Harvest\'s End!') elif day == '3' and month == 'Hearthfire': print('today is Tales and Tallows!') elif day == '13' and month == 'Frostfall': print('today is the Witches Festival!') elif day == '20' and month == 'Sun\'s Dusk': print('today is the Warriors\' Festival!') elif day == '15' and month == 'Evening Star': print('today is North Wind\'s Prayer!') elif day == '25' and month == 'Evening Star': print('today is Saturalia!') elif day == '31' and month == 'Evening Star': print('today is the Old Life Festival!') else: print('no holidays today') sstone = 'it is the month of' if months[month] == 'Morning Star': print(sstone, 'The Ritual') elif months[month] == 'Sun\'s Dawn': print(sstone, 'The Lover') elif months[month] == 'First Seed': print(sstone, 'The Lord') elif months[month] == 'Rain\'s Hand': print(sstone, 'The Mage') elif months[month] == 'Second Seed': print(sstone, 'The Shadow') elif months[month] == 'Midyear': print(sstone, 'The Steed Ritual') elif months[month] == 'Sun\'s Height': print(sstone, 'The Apprentice') elif months[month] == 'Last Seed': print(sstone, 'The Warrior') elif months[month] == 'Hearthfire': print(sstone, 'The Lady') elif months[month] == 'Frostfall': print(sstone, 'The Tower') elif months[month] == 'Sun\'s Dusk': print(sstone, 'The Atronach') elif months[month] == 'Evening Star': print(sstone, 'The Thief') else: print('there\'s been an error') input() exit(0)
def iswednesday(self, datestr): """判断是否为星期3""" if date.weekday(self.toDate(datestr)) == 2: return True else: return False
def compute_weekday(timestamp): date_str = timestamp.split('+')[0] date = datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%f') return date.weekday()
card.update_card() common.show_message("此卡已冻结!", "NOTICE") # 退出 if _choose == "0": quit_flag = True else: # 不是 admin 角色无权限 common.show_message("权限不够!", "ERROR") else: common.show_message("请先登录系统!", "NOTICE") userobj.login() if __name__ == "__main__": today = datetime.now().strftime("%Y-%m-%d") weekoftoday = date.weekday(datetime.now()) curruser = Users() # 初始化对账单 report.create_statement_main() # -------- 开始主程序 ------------------- exitflag = False while not exitflag: # 如果用户登录了,显示登录的界面; 未登录显示未登录的界面 if not curruser.islogin: print( template.index_default_menu.format( "", today, common.numtochr(weekoftoday))) else: print(
# Get today's date from the simple today() method from the date class today = date.today() print "Today's date is ", today # print out the date's individual components print "Date Components: ", today.day, today.month, today.year # retrieve today's weekday (0=Monday, 6=Sunday) print "Today's Weekday #: ", today.weekday() # Get the current time t = datetime.time(datetime.now()) print "The current time is ", t # weekday returns 0 (monday) through 6 (sunday) wd = date.weekday(today) # Days start at 0 for Monday days = [ "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday" ] print "Today is day number %d" % wd print "Which is a " + days[wd] # re-declaring the variable works f = "abc" print "whatever: " % f def main():
def queryset(self, request, queryset): """ Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`. """ # Compare the requested value (either '80s' or '90s') # to decide how to filter the queryset. import datetime, pytz tz = pytz.timezone('Asia/Bangkok') today_tz = datetime.datetime.now(tz=tz) from datetime import date if self.value() == 'today': today = today_tz #date.today() return queryset.filter(created__year=today.year, created__month=today.month, created__day=today.day).order_by('created') if self.value() == 'yesterday': import datetime # today = date.today() - datetime.timedelta(days=1) today = today_tz - datetime.timedelta(days=1) return queryset.filter(created__year=today.year, created__month=today.month, created__day=today.day).order_by('created') if self.value() == 'thisweek': import datetime date = today_tz #datetime.date.today() start_week = date - datetime.timedelta(date.weekday()) end_week = start_week + datetime.timedelta(7) return queryset.filter( created__range=[start_week, end_week]).order_by('created') if self.value() == 'lastweek': import datetime date = today_tz #datetime.date.today() date_lastweek = date - datetime.timedelta(days=7) start_week = date_lastweek - datetime.timedelta( date_lastweek.weekday()) end_week = start_week + datetime.timedelta(7) print(start_week, end_week) # date = end_week + datetime.timedelta(days=1) # start_week = date - datetime.timedelta(date.weekday()) # end_week = start_week + datetime.timedelta(7) return queryset.filter( created__range=[start_week, end_week]).order_by('created') if self.value() == 'thismonth': today = today_tz #date.today() # print('this month') return queryset.filter( created__year=today.year, created__month=today.month).order_by('created') if self.value() == 'lastmonth': import datetime # today = date.today().replace(day=1) - datetime.timedelta(days=1) today = today_tz.replace(day=1) - datetime.timedelta(days=1) # print('last month',today) return queryset.filter( created__year=today.year, created__month=today.month).order_by('created')
def move_ucr_data_into_aggregation_tables(date=None, intervals=2): date = date or datetime.utcnow().date() monthly_dates = [] # probably this should be run one time, for now I leave this in aggregations script (not a big cost) # but remove issues when someone add new table to mapping, also we don't need to add new rows manually # on production servers _update_ucr_table_mapping() first_day_of_month = date.replace(day=1) for interval in range(intervals - 1, 0, -1): # calculate the last day of the previous months to send to the aggregation script first_day_next_month = first_day_of_month - relativedelta(months=interval - 1) monthly_dates.append(first_day_next_month - relativedelta(days=1)) monthly_dates.append(date) db_alias = get_icds_ucr_db_alias() if db_alias: with connections[db_alias].cursor() as cursor: _create_aggregate_functions(cursor) _update_aggregate_locations_tables() state_ids = list(SQLLocation.objects .filter(domain=DASHBOARD_DOMAIN, location_type__name='state') .values_list('location_id', flat=True)) for monthly_date in monthly_dates: calculation_date = monthly_date.strftime('%Y-%m-%d') stage_1_tasks = [ icds_state_aggregation_task.si(state_id=state_id, date=monthly_date, func_name='_aggregate_gm_forms') for state_id in state_ids ] stage_1_tasks.extend([ icds_state_aggregation_task.si(state_id=state_id, date=monthly_date, func_name='_aggregate_df_forms') for state_id in state_ids ]) stage_1_tasks.extend([ icds_state_aggregation_task.si(state_id=state_id, date=monthly_date, func_name='_aggregate_cf_forms') for state_id in state_ids ]) stage_1_tasks.extend([ icds_state_aggregation_task.si(state_id=state_id, date=monthly_date, func_name='_aggregate_ccs_cf_forms') for state_id in state_ids ]) stage_1_tasks.extend([ icds_state_aggregation_task.si(state_id=state_id, date=monthly_date, func_name='_aggregate_child_health_thr_forms') for state_id in state_ids ]) stage_1_tasks.extend([ icds_state_aggregation_task.si(state_id=state_id, date=monthly_date, func_name='_aggregate_ccs_record_thr_forms') for state_id in state_ids ]) stage_1_tasks.extend([ icds_state_aggregation_task.si( state_id=state_id, date=monthly_date, func_name='_aggregate_child_health_pnc_forms' ) for state_id in state_ids ]) stage_1_tasks.extend([ icds_state_aggregation_task.si( state_id=state_id, date=monthly_date, func_name='_aggregate_ccs_record_pnc_forms' ) for state_id in state_ids ]) stage_1_tasks.extend([ icds_state_aggregation_task.si( state_id=state_id, date=monthly_date, func_name='_aggregate_delivery_forms' ) for state_id in state_ids ]) stage_1_tasks.extend([ icds_state_aggregation_task.si( state_id=state_id, date=monthly_date, func_name='_aggregate_bp_forms' ) for state_id in state_ids ]) stage_1_tasks.extend([ icds_state_aggregation_task.si(state_id=state_id, date=monthly_date, func_name='_aggregate_awc_infra_forms') for state_id in state_ids ]) stage_1_tasks.append(icds_aggregation_task.si(date=calculation_date, func_name='_update_months_table')) res_daily = icds_aggregation_task.delay(date=calculation_date, func_name='_daily_attendance_table') # https://github.com/celery/celery/issues/4274 stage_1_task_results = [stage_1_task.delay() for stage_1_task in stage_1_tasks] for stage_1_task_result in stage_1_task_results: stage_1_task_result.get(disable_sync_subtasks=False) res_child = chain( icds_state_aggregation_task.si( state_id=state_ids, date=calculation_date, func_name='_child_health_monthly_table' ), icds_aggregation_task.si(date=calculation_date, func_name='_agg_child_health_table'), ).apply_async() res_ccs = chain( icds_aggregation_task.si(date=calculation_date, func_name='_ccs_record_monthly_table'), icds_aggregation_task.si(date=calculation_date, func_name='_agg_ccs_record_table'), ).apply_async() res_daily.get(disable_sync_subtasks=False) res_ccs.get(disable_sync_subtasks=False) res_child.get(disable_sync_subtasks=False) res_ls_tasks = list() res_ls_tasks.extend([icds_state_aggregation_task.si(state_id=state_id, date=calculation_date, func_name='_agg_ls_awc_mgt_form') for state_id in state_ids ]) res_ls_tasks.extend([icds_state_aggregation_task.si(state_id=state_id, date=calculation_date, func_name='_agg_ls_vhnd_form') for state_id in state_ids ]) res_ls_tasks.extend([icds_state_aggregation_task.si(state_id=state_id, date=calculation_date, func_name='_agg_beneficiary_form') for state_id in state_ids ]) res_ls_tasks.append(icds_aggregation_task.si(date=calculation_date, func_name='_agg_ls_table')) res_awc = chain(icds_aggregation_task.si(date=calculation_date, func_name='_agg_awc_table'), *res_ls_tasks ).apply_async() res_awc.get(disable_sync_subtasks=False) first_of_month_string = monthly_date.strftime('%Y-%m-01') for state_id in state_ids: create_mbt_for_month.delay(state_id, first_of_month_string) if date.weekday() == 5: icds_aggregation_task.delay(date=date.strftime('%Y-%m-%d'), func_name='_agg_awc_table_weekly') chain( icds_aggregation_task.si(date=date.strftime('%Y-%m-%d'), func_name='aggregate_awc_daily'), email_dashboad_team.si(aggregation_date=date.strftime('%Y-%m-%d')) ).delay() _bust_awc_cache.delay()
def define_working_days_table(start_date, end_date): """ :return: Returns a data frame with all days in the defined time frame (start_date - end_date) The data frame has two columns: days and type :Days: contains all dates in the time frame :Type: the information if the day is a - working day (WD) - vacation day (paid time off - PTO) - public holiday (PH) - weekend (WE) - saturday and sunday """ #retrive objects from public_holidays tables an write them in a list public_holidays = [ item.days for item in models.public_holidays.objects.all() ] vacation_days = [item.days for item in models.vacation_days.objects.all()] all_days = [] number_of_days = end_date - start_date for n in range(number_of_days.days): day = start_date + timedelta(n) all_days.append({'days': day, 'type': "WD"}) workdays_index = [0, 1, 2, 3, 4] all_days_we = [] for item in all_days: if date.weekday(item['days']) in workdays_index: all_days_we.append({'days': item['days'], 'type': item['type']}) else: all_days_we.append({'days': item['days'], 'type': "WE"}) all_days_we_ph = [] for item in all_days_we: if item['days'] in public_holidays: all_days_we_ph.append({'days': item['days'], 'type': "PH"}) else: all_days_we_ph.append({'days': item['days'], 'type': item['type']}) all_days_we_ph_pto = [] for item in all_days_we_ph: if item['days'] in vacation_days: all_days_we_ph_pto.append({'days': item['days'], 'type': "PTO"}) else: all_days_we_ph_pto.append({ 'days': item['days'], 'type': item['type'] }) print( f"Number of days between start and end date: {len(all_days_we_ph_pto)}" ) print( f"Number of weekend days between start and end date: {len([1 for item in all_days_we_ph_pto if item['type'] == 'WE'])}" ) print( f"Number of public holidays between start and end date (minus public holidays): {len([1 for item in all_days_we_ph_pto if item['type'] == 'PH'])}" ) print( f"Number of vacation days between start and end date (minus public holidays and vacation days): {len([1 for item in all_days_we_ph_pto if item['type'] == 'PTO'])}" ) working_days = [] for item in all_days_we_ph_pto: if item['type'] == "WD": working_days.append({ 'days': item['days'], 'type': item['type'], 'working_hours': config.target_hours_per_day }) else: working_days.append({ 'days': item['days'], 'type': item['type'], 'working_hours': 0 }) working_days_df = pd.DataFrame(data=working_days) return working_days_df
def get_work_schedule(self, employee, date): schedule = self.env['resource.calendar.attendance'] res = {'schedule_start': False, 'schedule_end': False} ## IDEA: Perform if Work Shifting Module is installed try: restday_shift = self.env['shifting.schedule.restday'].search([ ('shifting_id.state', '=', 'approved'), ('shifting_id.employee_schedule_id', '=', employee.contract_id.resource_calendar_id.id), ('date_switch', '=',date) ]) if restday_shift[:1]: for rec in restday_shift.shifting_id.employee_ids: if rec.id == employee.id: return res schedule_shift = self.env['shifting.schedule'].search([ ('state', '=', 'approved'), ('employee_schedule_id', '=', employee.contract_id.resource_calendar_id.id), ('date_end', '>=', date), ('date_start', '<=', date) ], limit=1) if schedule_shift[:1]: for rec in schedule_shift.employee_ids: if rec.id == employee.id: res['schedule_start'] = datetime.combine(date, time(int(divmod((schedule_shift.start_hour * 60), 60)[0]),int(divmod((schedule_shift.start_hour * 60), 60)[1]))) if schedule_shift.start_hour > schedule_shift.end_hour: date += timedelta(days=1) res['schedule_end'] = datetime.combine(date, time(int(divmod((schedule_shift.end_hour * 60), 60)[0]),int(divmod((schedule_shift.end_hour * 60), 60)[1]))) return res except: pass # _logger.info("\n\n\nI Was called.\n\n") sched_ids = [i.id for i in schedule.search([('calendar_id', '=', employee.contract_id.resource_calendar_id.id), ('dayofweek', '=', date.weekday())])] if sched_ids: res['schedule_start'] = datetime.combine(date, time(int(divmod((schedule.browse(min(sched_ids)).hour_from * 60), 60)[0]),int(divmod((schedule.browse(min(sched_ids)).hour_from * 60), 60)[1]))) if schedule.browse(min(sched_ids)).hour_from > schedule.browse(max(sched_ids)).hour_to: date += timedelta(days=1) res['schedule_end'] = datetime.combine(date, time(int(divmod((schedule.browse(max(sched_ids)).hour_to * 60), 60)[0]),int(divmod((schedule.browse(max(sched_ids)).hour_to * 60), 60)[1]))) return res
def weekday_of_birth_date(date): """Takes a date object and returns the corresponding weekday string""" day = date.weekday() return calendar.day_name[day]
def get_last_weekday(cls, date, target_weekday): oneday = timedelta(days = 1) while date.weekday() != cls.calendar_enums[target_weekday]: date -= oneday return datetime.combine(date,datetime.min.time())
def forecast(idx): date = datetime.fromtimestamp(int(data['daily']['data'][idx]['time'])) day = calendar.day_name[date.weekday()] lo = data['daily']['data'][idx]['temperatureMin'] hi = data['daily']['data'][idx]['temperatureMax'] cond = data['currently']['summary'] nowtemp = data['currently']['temperature'] #if there is a weather alert for the area get the title to print later. if 'alerts' in data: warn = data['alerts'][idx]['title'] else: warn = None # uncomment these to print outputs to local shell/session # print(day) # print('low :' + str(lo) ) # print('high:' + str(hi)) # print('' + cond.replace(u'\u2013', '-').encode('utf-8')) # take care of pesky unicode dash # print('current temp: ' + str(nowtemp)) # if there is an alert print it rather than the summary # if warn is not None: # print('alerts: ' + str(warn)) # else: # print('Summary: ' + cond.replace(u'\u2013', '-').encode('utf-8')) #The follow preapres the data to send to Papirus hat #Show Day text.AddText((day), 0, 0, 18, Id="Line1", fontPath='/home/pi/PaPiRusWeather/fonts/Roboto-Bold.ttf') #Low temp and high temps for the day text.AddText(('low:' + str(lo) + ' high:' + str(hi)), 0, 30, fontsize, Id="Line2", fontPath='/home/pi/PaPiRusWeather/fonts/ElecSign.ttf') #Show current temp text.AddText(('Currently:' + str(nowtemp)), 0, 40, fontsize, Id="line3", fontPath='/home/pi/PaPiRusWeather/fonts/ElecSign.ttf') #if there is an alert print it rather than the summary #if there is not an alert print the summary if warn is not None: text.AddText(('' + str(warn)), 0, 50, fontsize, Id="Line4", fontPath='/home/pi/PaPiRusWeather/fonts/ElecSign.ttf') else: text.AddText(('' + cond.replace(u'\u2013', '-').encode('utf-8')), 0, 50, fontsize, Id="Line4", fontPath='/home/pi/PaPiRusWeather/fonts/ElecSign.ttf') #write it all out to the dispay text.WriteAll()
def isworkday(self, datestr): """判断是否为工作日""" if date.weekday(self.toDate(datestr)) in (0, 1, 2, 3, 4): return True else: return False
def day_of_week(date): if date is None: return None return date.weekday()
def issaturday(self, datestr): """判断是否为星期6""" if date.weekday(self.toDate(datestr)) == 5: return True else: return False
def isweekend(self, datestr): """判断是否为周末""" if date.weekday(self.toDate(datestr)) in (5, 6): return True else: return False
# acquire html content try: soup = BeautifulSoup(urllib2.urlopen(u"http://url", timeout=60), "html.parser") # 1 except Exception, e: handle_error(e, "Network Error.") return content = soup.select("html") # 2 # polyfill content = content + [None] * (7 - len(content)) from datetime import date content = content[date.weekday(date.today()) \ if not day else day[0] - 1] # 0 stands for monday in time module if not content: print("Nothing found.") return # prepare report text table = [(u"Status", u"ID", u"Name")] table += [(u"Update", p, p) for p in content] # 3 table += [(u"Normal", p, p) for p in content] # 4 # prettify table text = prettify_table(table)
def issunday(self, datestr): """判断是否为星期7""" if date.weekday(self.toDate(datestr)) == 6: return True else: return False
def weatherForecastLookUp(self, speech, language): speech = speech.replace(u".", "") viewType = "DAILY" if (speech.count("today") > 0 or speech.count("current") > 0 or speech.count(" for today") > 0) and language == "en-US": viewType = "HOURLY" speech = speech.replace("todays", "") speech = speech.replace("today", "") speech = speech.replace("currently", "") speech = speech.replace("current", "") speech = speech.replace(" for today", " in ") speech = speech.replace(" for ", " in ") if (speech.count("heute") > 0 or speech.count("moment") > 0 or speech.count(u"nächsten Stunden") > 0 or speech.count(u"für heute") > 0) and language == "de-DE": viewType = "HOURLY" speech = speech.replace("heute", "") speech = speech.replace("im moment", "") speech = speech.replace("momentan", "") speech = speech.replace("aktuelle", "") speech = speech.replace("aktuell", "") speech = speech.replace(u"in den nächsten Stunden", "") speech = speech.replace(u"für heute", "") if language == "en-US": speech = speech.replace(" for ", " in ") if language == "de-DE": speech = speech.replace(u"in den nächsten Tagen", "") speech = speech.replace(u"in den nächsten paar Tagen", "") speech = speech.replace(u"in der nächsten Woche", "") speech = speech.replace(u"nächste Woche", "") speech = speech.replace(u" für ", " in ") error = False view = AddViews(refId=self.refId, dialogPhase="Reflection") print weatherPlugin.localizations randomNumber = random.randint(0, 3) view.views = [ AssistantUtteranceView( weatherPlugin.localizations['weatherForecast']['search'] [randomNumber][language], weatherPlugin.localizations['weatherForecast']['search'] [randomNumber][language]) ] self.connection.send_object(view) countryOrCity = re.match("(?u).* in ([\w ]+)", speech, re.IGNORECASE) if countryOrCity != None: countryOrCity = countryOrCity.group(1).strip() print "found forecast" # lets see what we got, a country or a city... # lets use google geocoding API for that url = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false&language={1}".format( urllib.quote_plus(countryOrCity.encode("utf-8")), language) elif countryOrCity == None: currentLocation = self.getCurrentLocation() url = "http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=false&language={2}".format( str(currentLocation.latitude), str(currentLocation.longitude), language) # lets wait max 3 seconds jsonString = None try: jsonString = urllib2.urlopen(url, timeout=3).read() except: pass if jsonString != None: response = json.loads(jsonString) # lets see what we have... if response['status'] == 'OK': components = response['results'][0]['address_components'] types = components[0][ 'types'] # <- this should be the city or country if "country" in types: # OK we have a country as input, that sucks, we need the capital, lets try again and ask for capital also components = filter( lambda x: True if "country" in x['types'] else False, components) url = "http://maps.googleapis.com/maps/api/geocode/json?address=capital%20{0}&sensor=false&language={1}".format( urllib.quote_plus(components[0]['long_name']), language) # lets wait max 3 seconds jsonString = None try: jsonString = urllib2.urlopen(url, timeout=3).read() except: pass if jsonString != None: response = json.loads(jsonString) if response['status'] == 'OK': components = response['results'][0][ 'address_components'] # response could have changed, lets check again, but it should be a city by now if response['status'] == 'OK': # get latitude and longitude location = response['results'][0]['geometry']['location'] city = filter( lambda x: True if "locality" in x['types'] or "administrative_area_level_1" in x['types'] else False, components)[0]['long_name'] country = filter( lambda x: True if "country" in x['types'] else False, components)[0]['long_name'] state = filter( lambda x: True if "administrative_area_level_1" in x['types'] or "country" in x['types'] else False, components)[0]['short_name'] stateLong = filter( lambda x: True if "administrative_area_level_1" in x['types'] or "country" in x['types'] else False, components)[0]['long_name'] countryCode = filter( lambda x: True if "country" in x['types'] else False, components)[0]['short_name'] url = "http://api.wunderground.com/api/{0}/geolookup/conditions/forecast7day//hourly7day/astronomy/q/{1},{2}.json".format( weatherApiKey, location['lat'], location['lng']) # lets wait max 3 seconds jsonString = None try: jsonString = urllib2.urlopen(url, timeout=5).read() except: pass if jsonString != None: response = json.loads(jsonString) # lets see what we have... if response.has_key("error") == False: weatherTemp = dict() if response.has_key("current_observation"): if response.has_key("moon_phase"): if (int(response["moon_phase"]["current_time"] ["hour"]) > int(response["moon_phase"] ["sunset"]["hour"]) ) or (int(response["moon_phase"] ["current_time"]["hour"]) < int(response["moon_phase"]["sunrise"] ["hour"])): weatherTempNightTime = True else: weatherTempNightTime = False else: weatherTempNightTime = False conditionSwapper = SiriWeatherFunctions() dayOfWeek = [] # for i in range(1, 8): dayOfWeek.append(i % 7 + 1) tempNight = weatherTempNightTime weatherTemp["currentTemperature"] = str( response["current_observation"]["temp_c"]) dailyForecasts = [] for x in range(0, 6): forecastDate = date( int(response["forecast"]["simpleforecast"] ["forecastday"][x]["date"]["year"]), int(response["forecast"]["simpleforecast"] ["forecastday"][x]["date"]["month"]), int(response["forecast"]["simpleforecast"] ["forecastday"][x]["date"]["day"])) weatherTemp[ "tempCondition"] = conditionSwapper.swapCondition( conditionTerm=response["forecast"] ["simpleforecast"]["forecastday"][x] ["icon"], night=tempNight) dailyForecasts.append( SiriForecastAceWeathersDailyForecast( timeIndex=(dayOfWeek[date.weekday( forecastDate)]), highTemperature=response["forecast"] ["simpleforecast"]["forecastday"][x] ["high"]["celsius"], lowTemperature=response["forecast"] ["simpleforecast"]["forecastday"][x] ["low"]["celsius"], condition= SiriForecastAceWeathersConditions( conditionCode=weatherTemp[ "tempCondition"] ["conditionCode"], conditionCodeIndex=weatherTemp[ "tempCondition"] ["conditionCodeIndex"]))) tempNight = False hourlyForecasts = [] for x in range(0, 10): if response["hourly_forecast"][x]: if ( int(response["moon_phase"] ["current_time"]["hour"]) <= int(response["hourly_forecast"][x] ["FCTTIME"]["hour"]) ) or (int(response["forecast"] ["simpleforecast"]["forecastday"] [0]["date"]["day"]) < int(response["hourly_forecast"][x] ["FCTTIME"]["mday"]) ) or (int( response["forecast"] ["simpleforecast"]["forecastday"] [0]["date"]["month"]) < int(response["hourly_forecast"] [x]["FCTTIME"]["mon"])): if response.has_key( "hourly_forecast") == True: weatherTemp = dict() if response.has_key( "current_observation"): if response.has_key( "moon_phase"): if (int( response[ "moon_phase"] ["sunset"]["hour"] ) < int(response[ "hourly_forecast"] [x]["FCTTIME"] ["hour"]) ) or (int( response[ "moon_phase"] ["sunrise"]["hour"] ) > int(response[ "hourly_forecast"] [x]["FCTTIME"] ["hour"])): weatherTempCon = conditionSwapper.swapCondition( conditionTerm= response[ "hourly_forecast"] [x]["icon"], night=True) else: weatherTempCon = conditionSwapper.swapCondition( conditionTerm= response[ "hourly_forecast"] [x]["icon"], night=False) else: weatherTempCon = conditionSwapper.swapCondition( conditionTerm=response[ "hourly_forecast"] [x]["icon"], night=True) hourlyForecasts.append( SiriForecastAceWeathersHourlyForecast( timeIndex=response[ "hourly_forecast"][x] ["FCTTIME"]["hour"], chanceOfPrecipitation=int( response["hourly_forecast"] [x]["pop"]), temperature=response[ "hourly_forecast"][x] ["temp"]["metric"], condition= SiriForecastAceWeathersConditions( conditionCode= weatherTempCon[ "conditionCode"], conditionCodeIndex= weatherTempCon[ "conditionCodeIndex"])) ) weatherTemp[ "currentCondition"] = conditionSwapper.swapCondition( conditionTerm=response[ "current_observation"]["icon"], night=weatherTempNightTime) currentTemperature = str( response["current_observation"]["temp_c"]) currentDate = date( int(response["forecast"]["simpleforecast"] ["forecastday"][0]["date"]["year"]), int(response["forecast"]["simpleforecast"] ["forecastday"][0]["date"]["month"]), int(response["forecast"]["simpleforecast"] ["forecastday"][0]["date"]["day"])) view = AddViews(self.refId, dialogPhase="Summary") currentConditions = SiriForecastAceWeathersCurrentConditions( dayOfWeek=dayOfWeek[int( date.weekday(currentDate))], temperature=currentTemperature, condition=SiriForecastAceWeathersConditions( conditionCode=weatherTemp[ "currentCondition"]["conditionCode"], conditionCodeIndex=weatherTemp[ "currentCondition"] ["conditionCodeIndex"])) aceWethers = [ SiriForecastAceWeathers( extendedForecastUrl=response["location"] ["wuiurl"], currentConditions=currentConditions, hourlyForecasts=hourlyForecasts, dailyForecasts=dailyForecasts, weatherLocation= SiriForecastAceWeathersWeatherLocation(), units=SiriForecastAceWeathersUnits(), view=viewType, ) ] weather = SiriForecastSnippet( aceWeathers=aceWethers) speakCountry = stateLong if country == "United States" else country if language == "de-DE": speakCountry = stateLong + " (" + country + ")" if country == "USA" else country randomNumber = random.randint(0, 2) view.views = [ AssistantUtteranceView( text=weatherPlugin.localizations[ 'weatherForecast']['forecast'] [viewType][randomNumber][language].format( city, speakCountry), speakableText=weatherPlugin.localizations[ 'weatherForecast']['forecast'] [viewType][randomNumber][language].format( city, speakCountry), dialogIdentifier= "Weather#forecastCommentary"), weather ] self.sendRequestWithoutAnswer(view) else: error = True else: error = True else: error = True else: error = True else: error = True if error: self.say(weatherPlugin.localizations['weatherForecast']['failure'] [language]) self.complete_request()
def isfriday(self, datestr): """判断是否为星期5""" if date.weekday(self.toDate(datestr)) == 4: return True else: return False