def weekday_calendar(self):
"""
Append the weekday to each date for the calendar year.
:return (list) of tuples ((str) weekday, datetime.date)
"""
_weekday_calendar = set()
for month in self.year_calendar:
for week in month:
for day in week:
if day.year == self.year:
_weekday_calendar.add(
(calendar.day_name[day.weekday()], day)
)
return sorted(list(_weekday_calendar), key=lambda x: x[1])
python类day_name()的实例源码
def _rashid_tibia(self):
"""Get Rashid's Location"""
current_date = date.today()
if calendar.day_name[current_date.weekday()] == "Sunday":
await self.bot.say("On Sundays you can find him in Carlin depot, one floor above.")
elif calendar.day_name[current_date.weekday()] == "Monday":
await self.bot.say("On Mondays you can find him in Svargrond, in Dankwart's tavern, south of the temple.")
elif calendar.day_name[current_date.weekday()] == "Tuesday":
await self.bot.say("On Tuesdays you can find him in Liberty Bay, in Lyonel's tavern, west of the depot.")
elif calendar.day_name[current_date.weekday()] == "Wednesday":
await self.bot.say("On Wednesdays you can find him in Port Hope, in Clyde's tavern, north of the ship.")
elif calendar.day_name[current_date.weekday()] == "Thursday":
await self.bot.say("On Thursdays you can find him in Ankrahmun, in Arito's tavern, above the post office.")
elif calendar.day_name[current_date.weekday()] == "Friday":
await self.bot.say("On Fridays you can find him in Darashia, in Miraia's tavern, south of the guildhalls.")
elif calendar.day_name[current_date.weekday()] == "Saturday":
await self.bot.say("On Saturdays you can find him in Edron, in Mirabell's tavern, above the depot.")
else:
pass
def convertToDay(toks):
now = datetime.now()
if "wkdayRef" in toks:
todaynum = now.weekday()
daynames = [n.lower() for n in calendar.day_name]
nameddaynum = daynames.index(toks.wkdayRef.day.lower())
if toks.wkdayRef.dir > 0:
daydiff = (nameddaynum + 7 - todaynum) % 7
else:
daydiff = -((todaynum + 7 - nameddaynum) % 7)
toks["absTime"] = datetime(now.year, now.month, now.day)+timedelta(daydiff)
else:
name = toks.name.lower()
toks["absTime"] = {
"now" : now,
"today" : datetime(now.year, now.month, now.day),
"yesterday" : datetime(now.year, now.month, now.day)+timedelta(-1),
"tomorrow" : datetime(now.year, now.month, now.day)+timedelta(+1),
}[name]
def number_to_day(self, day_number):
"""Returns localized day name by its CRON number
Args:
day_number: Number of a day
Returns:
Day corresponding to day_number
Raises:
IndexError: When day_number is not found
"""
return [
calendar.day_name[6],
calendar.day_name[0],
calendar.day_name[1],
calendar.day_name[2],
calendar.day_name[3],
calendar.day_name[4],
calendar.day_name[5]
][day_number]
def GetSchedule(self):
"""
Get the cleaning schedule for this robot
Returns:
A dictionary representing the schedule per day (dict)
"""
res = self._PostToRobot("get", "week")
schedule = {}
for idx in range(7):
cal_day_idx = idx - 1
if cal_day_idx < 0:
cal_day_idx = 6
schedule[calendar.day_name[cal_day_idx]] = {
"clean" : True if res["cycle"][idx] == "start" else False,
"startTime" : datetime.time(res["h"][idx], res["m"][idx])
}
return schedule
def number_to_day(self, day_number):
"""Returns localized day name by its CRON number
Args:
day_number: Number of a day
Returns:
Day corresponding to day_number
Raises:
IndexError: When day_number is not found
"""
# ADE force locale first...
import locale
locale.setlocale(locale.LC_ALL, '')
return [
calendar.day_name[6],
calendar.day_name[0],
calendar.day_name[1],
calendar.day_name[2],
calendar.day_name[3],
calendar.day_name[4],
calendar.day_name[5]
][day_number]
def finish_get_date(self, unix_time, dst_offset):
"""Converts date from unix time to string.
Args:
dst_offset: (bool) Set to True to offset time received from
open weather API by daylight savings time.
unix_time (int): Time given in seconds from beginning of the
epoch as on unix machines.
Returns:
name_of_day (str): Name of the day on date.
date_str (str): Date in string representation.
"""
if dst_offset:
dst_offset = self.v_link["timezone"]["dstOffset"] * 3600
else:
dst_offset = 0
date = datetime.datetime.utcfromtimestamp(unix_time + dst_offset)
date_str = date.strftime("%d/%m/%Y")
name_of_day = calendar.day_name[date.weekday()]
return name_of_day, date_str
def cb_backup_bucket(bucket, backup_method = ""):
if backup_method == "":
today = date.today()
day = calendar.day_name[today.weekday()]
# Run DB backup with complete/diff/accu in different days
backup_method = weekday_method.get(day)
backup_command = cb_backup_command(bucket, backup_method)
log.info("Backup Couchbase bucket: %s, method: %s" % (bucket, backup_method))
log.info("Run command: %s" % (backup_command))
# TODO: get command output
returncode = subprocess.call(backup_command, shell=True)
if returncode != 0:
log.error("Backup fails for %s" % (bucket))
sys.exit(returncode)
################################################################################
def getDateWeekday(weekday,eventHour):
day_evaluate = weekday
today = datetime.datetime.strptime(time.strftime("%x"),"%m/%d/%y")
if ('am' in eventHour) or ('pm' in eventHour) or ('AM' in eventHour) or ('PM' in eventHour):
start_hour = datetime.datetime.strptime(eventHour, "%I:%M %p").hour
start_minute = datetime.datetime.strptime(eventHour, "%I:%M %p").minute
else:
start_hour = datetime.datetime.strptime(eventHour, "%I:%M").hour
start_minute = datetime.datetime.strptime(eventHour, "%I:%M").minute
for i in range(1,8):
date = today + datetime.timedelta(days=i)
day_name = date.strftime("%A")
if (day_evaluate.upper() == day_name.upper()):
date = date.replace(hour=start_hour, minute=start_minute)
return date.isoformat() + gmt
def cdow(date_or_year, month_int=1, day_int=1): #----------------------------<<<
"""Convert a date or year/month/day to a day-of-week string.
date_or_year = a date/datetime, or year <int>
If a year value is passed, then month_int
and day_int are required.
month_int = month as <int>
day_int = day as <int>
Returns a weekday name (e.g., "Tuesday").
"""
if isinstance(date_or_year, datetime.datetime):
return calendar.day_name[date_or_year.weekday()]
else:
thedate = datetime.date(date_or_year, month_int, day_int)
return calendar.day_name[thedate.weekday()]
def getDateWeekday(weekday,eventHour):
day_evaluate = weekday
today = datetime.datetime.strptime(time.strftime("%x"),"%m/%d/%y")
if ('am' in eventHour) or ('pm' in eventHour) or ('AM' in eventHour) or ('PM' in eventHour):
start_hour = datetime.datetime.strptime(eventHour, "%I:%M %p").hour
start_minute = datetime.datetime.strptime(eventHour, "%I:%M %p").minute
else:
start_hour = datetime.datetime.strptime(eventHour, "%I:%M").hour
start_minute = datetime.datetime.strptime(eventHour, "%I:%M").minute
for i in range(1,8):
date = today + datetime.timedelta(days=i)
day_name = date.strftime("%A")
if (day_evaluate.upper() == day_name.upper()):
date = date.replace(hour=start_hour, minute=start_minute)
return date.isoformat() + gmt
def __calc_weekday(self):
# Set self.a_weekday and self.f_weekday using the calendar
# module.
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
self.a_weekday = a_weekday
self.f_weekday = f_weekday
def __init__(self, month, year, indent_level, indent_style):
'x.__init__(...) initializes x'
calendar.setfirstweekday(calendar.SUNDAY)
matrix = calendar.monthcalendar(year, month)
self.__table = HTML_Table(len(matrix) + 1, 7, indent_level, indent_style)
for column, text in enumerate(calendar.day_name[-1:] + calendar.day_name[:-1]):
self.__table.mutate(0, column, '<b>%s</b>' % text)
for row, week in enumerate(matrix):
for column, day in enumerate(week):
if day:
self.__table.mutate(row + 1, column, '<b>%02d</b>\n<hr>\n' % day)
self.__weekday, self.__alldays = calendar.monthrange(year, month)
self.__weekday = ((self.__weekday + 1) % 7) + 6
def day(self):
'''Random day of week'''
await self.bot.embed_reply(random.choice(calendar.day_name))
def __calc_weekday(self):
# Set self.a_weekday and self.f_weekday using the calendar
# module.
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
self.a_weekday = a_weekday
self.f_weekday = f_weekday
def __calc_weekday(self):
# Set self.a_weekday and self.f_weekday using the calendar
# module.
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
self.a_weekday = a_weekday
self.f_weekday = f_weekday
def timetable(values, data):
today = calendar.day_name[date.today().weekday()].lower()
tomorrow = calendar.day_name[(date.today().weekday() + 1) % 7].lower()
#timetable = values['timetable']
try:
time = values['time'][0]['value']
except KeyError:
time = 'today'
if time == 'today':
time = today
elif time == 'tomorrow':
time = tomorrow
if time == 'sunday':
return "Sunday is not a working day."
response = "The timetable for {} is : \n\n ".format(time.upper())
for subj in data[time]:
t, sub = subj
response += "({}) - {} \n\n".format(t,sub)
if len(data[time]) == 0:
return "There are no classes or {} is a holiday".format(time.upper())
return response
def __calc_weekday(self):
# Set self.a_weekday and self.f_weekday using the calendar
# module.
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
self.a_weekday = a_weekday
self.f_weekday = f_weekday
def formatShowText(channel, show, currentTime, formatString):
language = ""
when = ""
if " - " in channel.name:
chanName = channel.name.split(" - ")[1]
else:
chanName = channel.name
if show is None:
retVal = formatString.replace("{ch}", channel.channel_id).replace("{chname}", chanName)
else:
if "language" in show and show['language'].upper() != "US":
language = show['language'].upper()
if "720p" in chanName.lower():
chanName = chanName.replace(" 720P", "HD")
showTime = SmoothUtils.GetDateTimeNative(show['time'])
if showTime > currentTime:
if showTime.date() == currentTime.date():
when = "LATER"
else:
when = calendar.day_name[showTime.weekday()][:3].upper()
if "category" in show and show["name"].startswith(show["category"] + ":") and show["category"] != "News":
show["name"] = show["name"].replace(show["category"] + ":", "").strip()
retVal = formatString.replace("{ch}", channel.channel_id).replace("{chname}", chanName).replace("{title}", show['name']).replace("{qual}", show["quality"].replace("hqlq", "").replace("unk", "")).replace("{time}", SmoothUtils.GetShowTimeText(show)).replace("{lang}", language).replace("{when}", when).replace("{cat}", show['category'])
return retVal.replace("()", "").replace(" ", " ").strip()
def test_name(self):
for i, day_name in enumerate(calendar.day_abbr):
self.assertEqual(WeekdaySetBuilder().build(day_name), {i})
for i, day_name in enumerate(calendar.day_name):
self.assertEqual(WeekdaySetBuilder().build(day_name), {i})
def GetTime(self):
"""
Get the time this robot is set to
Returns:
A dictionary with the time of day and day of week (dict)
"""
result = self._PostToRobot("get", "time")
day_idx = [idx for idx, day in enumerate(calendar.day_abbr) if day.lower() == result["d"]][0]
return {
"time" : datetime.time(result["h"], result["m"]),
"weekday" : calendar.day_name[day_idx]
}
def SetSchedule(self, newSchedule):
"""
Set the cleaning schedule for this robot.
The easiest way to use this function is to call GetSchedule, modify
the result, and use that as the input to this function
Args:
schedule: the schedule to set (dict)
"""
# Sort calendar day names into the order the robot expects
days = {}
for cal_idx, dayname in enumerate(calendar.day_name):
idx = cal_idx + 1 if cal_idx < 6 else 0
days[idx] = dayname
sched = collections.OrderedDict([
("cycle", []),
("h", []),
("m", [])
])
for idx in sorted(days):
dayname = days[idx]
if newSchedule[dayname]["clean"]:
sched["cycle"].append("start")
else:
sched["cycle"].append("none")
sched["h"].append(newSchedule[dayname]["startTime"].hour)
sched["m"].append(newSchedule[dayname]["startTime"].minute)
self._PostToRobot("set", ["week", sched])
def most_frequent_days(year):
"""
List of most frequent days of the week in the given year
"""
firstweek = set(range(datetime(year, 1, 1).weekday(), 7)) # weekday 0..6
lastweek = set(range(datetime(year, 12, 31).isoweekday())) # isoweekday 1..7
return [day_name[day] for day in sorted((firstweek & lastweek) or (firstweek | lastweek))]
def __calc_weekday(self):
# Set self.a_weekday and self.f_weekday using the calendar
# module.
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
self.a_weekday = a_weekday
self.f_weekday = f_weekday
def __calc_weekday(self):
# Set self.a_weekday and self.f_weekday using the calendar
# module.
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
self.a_weekday = a_weekday
self.f_weekday = f_weekday
def __calc_weekday(self):
# Set self.a_weekday and self.f_weekday using the calendar
# module.
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
self.a_weekday = a_weekday
self.f_weekday = f_weekday
danceschool_tags.py 文件源码
项目:django-danceschool
作者: django-danceschool
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def readable_weekday(weekday):
try:
return day_name[weekday]
except (TypeError,IndexError):
return None
def __calc_weekday(self):
# Set self.a_weekday and self.f_weekday using the calendar
# module.
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
self.a_weekday = a_weekday
self.f_weekday = f_weekday
def __calc_weekday(self):
# Set self.a_weekday and self.f_weekday using the calendar
# module.
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
self.a_weekday = a_weekday
self.f_weekday = f_weekday
def get_date_desc(e):
d = get_date(e)
diff = d - datetime.datetime.today()
if diff > datetime.timedelta(14):
return d.strftime("%d %B")
else:
return calendar.day_name[d.weekday()]