예제 #1
0
    def test_setup_locale(self):
        monday = calendar.day_abbr[0]
        first_weekday = calendar.firstweekday()

        setup_locale('uk_UA.UTF-8')
        self.assertNotEqual(calendar.day_abbr[0], monday)
        self.assertEqual(calendar.firstweekday(), first_weekday)
예제 #2
0
    def test_setup_locale_with_first_weekday(self):
        first_weekday = calendar.firstweekday()

        setup_locale('uk_UA.UTF-8', 1)
        self.assertEqual(calendar.firstweekday(), 1)

        setup_locale('en_US.UTF-8', first_weekday)
def calendar_():
  cal = calendar.month(2017, 6)  # by default w=2 l=1
  print cal  # 2017年6月份日历

  print '--------------------'
  # calendar内置函数
  #calendar of year 2017: c=distance(month); l=line(week); w=distance(day)
  print calendar.calendar(2017, w=2, l=1, c=6)  #lenth(line)= 21* W+18+2* C

  print calendar.firstweekday() # start weekday, 0 by default, i.e. Monday
  # calendar.setfirstweekday(weekday)  # 0(Monday) to 6(Sunday)

  print calendar.isleap(2017) # return True or False
  print calendar.leapdays(2000, 2016) # number of leap years between year 1 and year 2

  print calendar.month(2017, 6)
  print calendar.monthcalendar(2017, 6)

  print calendar.monthrange(2017, 6)  # return (a, b)  a=starting weekday b=days in month

  calendar.prcal(2017, w=2, l=1, c=4)  # equals to print calendar.calendar(2017, w=2, l=1, c=4)
  calendar.prmonth(2017, 6) # equals to print calendar.month(2017, 6)

  print calendar.timegm(time.localtime()) #和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间辍

  print calendar.weekday(2017, 6, 30) # calendar.weekday(year,month,day) return date code
예제 #4
0
    def test_setup_locale_with_first_weekday(self):
        first_weekday = calendar.firstweekday()

        setup_locale('uk_UA.UTF-8', 1)
        self.assertEqual(calendar.firstweekday(), 1)

        setup_locale('en_US.UTF-8', first_weekday)
예제 #5
0
def test_setup_locale():
    monday = calendar.day_abbr[0]
    first_weekday = calendar.firstweekday()

    setup_locale("uk_UA.UTF-8")
    assert calendar.day_abbr[0] != monday
    assert calendar.firstweekday() == first_weekday
예제 #6
0
def test_setup_locale_with_first_weekday():
    first_weekday = calendar.firstweekday()

    setup_locale("uk_UA.UTF-8", 1)
    assert calendar.firstweekday() == 1

    setup_locale("en_US.UTF-8", first_weekday)
예제 #7
0
    def test_setup_locale(self):
        monday = calendar.day_abbr[0]
        first_weekday = calendar.firstweekday()

        setup_locale('uk_UA.UTF-8')
        self.assertNotEqual(calendar.day_abbr[0], monday)
        self.assertEqual(calendar.firstweekday(), first_weekday)
예제 #8
0
def calendar_():
    cal = calendar.month(2017, 6)  # by default w=2 l=1
    print cal  # 2017年6月份日历

    print '--------------------'
    # calendar内置函数
    #calendar of year 2017: c=distance(month); l=line(week); w=distance(day)
    print calendar.calendar(2017, w=2, l=1, c=6)  #lenth(line)= 21* W+18+2* C

    print calendar.firstweekday()  # start weekday, 0 by default, i.e. Monday
    # calendar.setfirstweekday(weekday)  # 0(Monday) to 6(Sunday)

    print calendar.isleap(2017)  # return True or False
    print calendar.leapdays(
        2000, 2016)  # number of leap years between year 1 and year 2

    print calendar.month(2017, 6)
    print calendar.monthcalendar(2017, 6)

    print calendar.monthrange(
        2017, 6)  # return (a, b)  a=starting weekday b=days in month

    calendar.prcal(
        2017, w=2, l=1,
        c=4)  # equals to print calendar.calendar(2017, w=2, l=1, c=4)
    calendar.prmonth(2017, 6)  # equals to print calendar.month(2017, 6)

    print calendar.timegm(
        time.localtime())  #和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间辍

    print calendar.weekday(
        2017, 6, 30)  # calendar.weekday(year,month,day) return date code
예제 #9
0
 def test_configuring_week_start_day(self):
   args = [ '--start-day=sun', 'minimal-blank.svg' ]
   e = SVGCalendar()
   e.affect( args, False )
   self.assertEqual( calendar.firstweekday(), 6 )
   args = [ '--start-day=mon', 'minimal-blank.svg' ]
   e = SVGCalendar()
   e.affect( args, False )
   self.assertEqual( calendar.firstweekday(), 0 )
예제 #10
0
 def test_setfirstweekday(self):
     self.assertRaises(ValueError, calendar.setfirstweekday, 'flabber')
     self.assertRaises(ValueError, calendar.setfirstweekday, -1)
     self.assertRaises(ValueError, calendar.setfirstweekday, 200)
     orig = calendar.firstweekday()
     calendar.setfirstweekday(calendar.SUNDAY)
     self.assertEqual(calendar.firstweekday(), calendar.SUNDAY)
     calendar.setfirstweekday(calendar.MONDAY)
     self.assertEqual(calendar.firstweekday(), calendar.MONDAY)
     calendar.setfirstweekday(orig)
예제 #11
0
    def test_sets_day_abbreviations_to_show_above_calendar(self):
        skeleton = self._makeOne(2009, 8)

        self.assertEqual(len(skeleton.day_abbrs), 7)
        
        sunday = calendar.day_abbr[ calendar.firstweekday() ]
        self.assertEqual(skeleton.day_abbrs[0], sunday)
예제 #12
0
 def printDay(self, j):
     """ Print a given day """
     cel = createText(self.marginl + ((j.weekday()-calendar.firstweekday())%7)*self.colSize,
                      self.calHeight + self.rowSize,
                      self.colSize/5, self.rowSize)
     setText(str(j.day), cel)
     setStyle(self.pStyleDate, cel)
예제 #13
0
def mifunction():
    print("Hola esto es una funcion")
    print(calendar.weekheader(8))
    print(calendar.firstweekday())
    print(calendar.month(2019, 8))
    print(calendar.monthcalendar(2019, 8))
    print(calendar.calendar(2019))
예제 #14
0
 def printDay(self, j):
     """ Print a given day """
     cel = createText(self.gmean + self.marginl,
                      self.margint + (1 + (j.weekday()-calendar.firstweekday())%7) * self.rowSize,
                      self.width - self.gmean, self.rowSize)
     setText(str(j.day), cel)
     setStyle(self.pStyleDate, cel)
    def should_run(self):

        import time
        import calendar
        dayNumber = int(time.strftime('%d'))
        year = int(time.strftime('%Y'))
        month = int(time.strftime('%m'))
        dayrange = calendar.monthrange(year, month)
        if 'DAY' in self.report['SCHEDULE']['SETTINGS']:
            day = int(self.report['SCHEDULE']['SETTINGS']['DAY'])
        else:
            day = 0
        if dayNumber == day:
            return True
        elif 'relative' in self.report['SCHEDULE']['SETTINGS']:
            relative = self.report['SCHEDULE']['SETTINGS']['RELATIVE'].upper()
            if relative == 'LAST' and dayNumber == dayrange[1]:
                return True
            if relative == 'FIRST' and dayNumber == dayrange[0]:
                return True
            if relative == 'FIRSTWEEKDAY' and dayNumber == calendar.firstweekday(
            ) and dayNumber <= 3:
                return True
        else:
            return False
        return False
예제 #16
0
    def get_datetime_formats(self):
        dtformats = {}

        dtformats["SHORT_DATE"] = get_format("DATE_INPUT_FORMATS",
                                             get_language())[0]
        dtformats["TIME"] = get_format("TIME_INPUT_FORMATS", get_language())[0]
        dtformats["SHORT_DATETIME"] = get_format("DATETIME_INPUT_FORMATS",
                                                 get_language())[0]
        firstweekday = calendar.firstweekday() + 1
        if firstweekday == 7:
            firstweekday = 0
        day_names = calendar.day_name[-1:] + calendar.day_name[:-1]
        day_abbr = calendar.day_abbr[-1:] + calendar.day_abbr[:-1]
        dtformats["DAYS"] = mark_safe(json.dumps([_(day)
                                                  for day in day_names]))
        dtformats["DAYS_SHORT"] = mark_safe(
            json.dumps([_(day) for day in day_abbr]))
        dtformats["DAYS_MIN"] = mark_safe(
            json.dumps([_(day)[:2] for day in day_abbr]))
        dtformats["MONTHS"] = mark_safe(
            json.dumps(
                [_(day).capitalize() for day in calendar.month_name[1:]]))
        dtformats["MONTHS_SHORT"] = mark_safe(
            json.dumps([_(day) for day in calendar.month_abbr[1:]]))
        dtformats["TODAY"] = _("Today")
        dtformats["CLEAR"] = _("Clear")
        dtformats["FIRST_DAY"] = firstweekday

        return dtformats
예제 #17
0
    def get_datetime_formats(self):
        dtformats = {}

        dtformats['SHORT_DATE'] = get_format('DATE_INPUT_FORMATS',
                                             get_language())[0]
        dtformats['TIME'] = get_format('TIME_INPUT_FORMATS', get_language())[0]
        dtformats['SHORT_DATETIME'] = get_format('DATETIME_INPUT_FORMATS',
                                                 get_language())[0]
        firstweekday = calendar.firstweekday() + 1
        if firstweekday == 7:
            firstweekday = 0
        day_names = calendar.day_name[-1:] + calendar.day_name[:-1]
        day_abbr = calendar.day_abbr[-1:] + calendar.day_abbr[:-1]
        dtformats['DAYS'] = mark_safe(json.dumps([_(day)
                                                  for day in day_names]))
        dtformats['DAYS_SHORT'] = mark_safe(
            json.dumps([_(day) for day in day_abbr]))
        dtformats['DAYS_MIN'] = mark_safe(
            json.dumps([_(day)[:2] for day in day_abbr]))
        dtformats['MONTHS'] = mark_safe(
            json.dumps(
                [_(day).capitalize() for day in calendar.month_name[1:]]))
        dtformats['MONTHS_SHORT'] = mark_safe(
            json.dumps([_(day) for day in calendar.month_abbr[1:]]))
        dtformats['TODAY'] = _('Today')
        dtformats['CLEAR'] = _('Clear')
        dtformats['FIRST_DAY'] = firstweekday

        return dtformats
예제 #18
0
파일: test_utils.py 프로젝트: boothead/karl
    def test_sets_day_abbreviations_to_show_above_calendar(self):
        skeleton = self._makeOne(2009, 8)

        self.assertEqual(len(skeleton.day_abbrs), 7)
        
        sunday = calendar.day_abbr[ calendar.firstweekday() ]
        self.assertEqual(skeleton.day_abbrs[0], sunday)
예제 #19
0
 def printDay(self, j):
     """ Print a given day """
     cel = createText(self.gmean + self.marginl,
                      self.margint + (1 + (j.weekday()-calendar.firstweekday())%7) * self.rowSize,
                      self.width - self.gmean, self.rowSize)
     setText(str(j.day), cel)
     setStyle(self.pStyleDate, cel)
예제 #20
0
 def printDay(self, j):
     """ Print a given day """
     cel = createText(self.marginl + ((j.weekday()-calendar.firstweekday())%7)*self.colSize,
                      self.calHeight + self.rowSize,
                      self.colSize/5, self.rowSize)
     setText(str(j.day), cel)
     setStyle(self.pStyleDate, cel)
예제 #21
0
 def __get_firstweekday(self):
     first = getattr(self, '_firstweekday', None)
     if first is not None:
         return first
     first = int(
         self.request.form.get('firstweekday', calendar.firstweekday()))
     self._firstweekday = first
     return first
예제 #22
0
 def __get_firstweekday(self):
     first = getattr(self, '_firstweekday', None)
     if first is not None:
         return first
     first = int(self.request.form.get('firstweekday', 
                                       calendar.firstweekday()))
     self._firstweekday = first
     return first
예제 #23
0
 def testPassThruByMinute(self):
     newWkst = (calendar.firstweekday() + 2) % 7
     self.failUnlessParseMatches(
         "FREQ=HOURLY;BYMINUTE=15,45",
         False,
         {'freq':rrule.HOURLY, 'interval':1},
         {'byminute': (15, 45)} # Test passthru of wkst
     )
예제 #24
0
    def _init_headings(self):
        firstday = calendar.firstweekday()

        day_names = list(calendar.day_name)
        self.day_names = day_names[firstday:] + day_names[:firstday]

        day_abbrs = list(calendar.day_abbr)
        self.day_abbrs = day_abbrs[firstday:] + day_names[:firstday]
예제 #25
0
 def testPassThruBySecond(self):
     newWkst = (calendar.firstweekday() + 2) % 7
     self.failUnlessParseMatches(
         "FREQ=HOURLY;BYMINUTE=15,45;BYSECOND=11,21,31,41",
         False,
         {'freq':rrule.HOURLY, 'interval':1},
         {'byminute': (15, 45),
          'bysecond': (11, 21, 31, 41)} # Test passthru of wkst
     )
예제 #26
0
 def test_default_names_list(self):
     """Test default names"""
     effect = self.assertEffect()
     self.assertEqual(effect.options.month_names[0], 'January')
     self.assertEqual(effect.options.month_names[11], 'December')
     self.assertEqual(effect.options.day_names[0], 'Sun')
     self.assertEqual(effect.options.day_names[6], 'Sat')
     self.assertEqual(effect.options.year, datetime.datetime.today().year)
     self.assertEqual(calendar.firstweekday(), 6)
예제 #27
0
파일: test_month.py 프로젝트: boothead/karl
    def test_sets_day_headings_for_template_to_show_above_calendar(self):
        focus_at = datetime.datetime(2009, 8, 26)
        now_at   = datetime.datetime.now()

        presenter = self._makeOne(focus_at, now_at, dummy_url_for)
        self.assertEqual(len(presenter.day_headings), 7)
        
        sunday = calendar.day_name[ calendar.firstweekday() ]
        self.assertEqual(presenter.day_headings[0], sunday)
예제 #28
0
파일: test_month.py 프로젝트: iotest3/new
    def test_sets_day_headings_for_template_to_show_above_calendar(self):
        focus_at = datetime.datetime(2009, 8, 26)
        now_at   = datetime.datetime.now()

        presenter = self._makeOne(focus_at, now_at, dummy_url_for)
        self.assertEqual(len(presenter.day_headings), 7)
        
        sunday = calendar.day_name[ calendar.firstweekday() ]
        self.assertEqual(presenter.day_headings[0], sunday)
예제 #29
0
파일: HTMLCalendar.py 프로젝트: goerz/pyala
	def _renderTemplate(self, node, year, month, links, dayrenderer):
		fd = calendar.firstweekday()
		calendar.setfirstweekday(self._firstWeekday)
		weeks = calendar.monthcalendar(year, month) # a list of seven-item lists
		calendar.setfirstweekday(fd)
		if len(weeks) == 5:
			weeks.append([0, 0, 0, 0, 0, 0, 0])
		node.caption.content = self._months[month - 1] + " " + str(year) # set table caption
		node.week.repeat(self._renderWeek, weeks, links, self._WeekendTrackerGen(self._isSundayFirst), year, month, dayrenderer) # render weekly rows
예제 #30
0
 def printWeekNo(self, week):
     """ Print the week number for the given week"""
     weekCel = createText(self.marginl, self.calHeight, self.width, self.rowSize)
     # Week number: of this week's Thursday.
     # See http://docs.python.org/library/datetime.html#datetime.date.isocalendar
     # Note that week calculation isn't perfectly universal yet:
     # http://en.wikipedia.org/wiki/Week_number#Week_number
     setText(str(week[(calendar.THURSDAY-calendar.firstweekday())%7].isocalendar()[1]), weekCel)
     setStyle(self.pStyleWeekNo, weekCel)
예제 #31
0
 def printWeekNo(self, week):
     """ Print the week number for the given week"""
     weekCel = createText(self.marginl, self.calHeight, self.width, self.rowSize)
     # Week number: of this week's Thursday.
     # See http://docs.python.org/library/datetime.html#datetime.date.isocalendar
     # Note that week calculation isn't perfectly universal yet:
     # http://en.wikipedia.org/wiki/Week_number#Week_number
     setText(str(week[(calendar.THURSDAY-calendar.firstweekday())%7].isocalendar()[1]), weekCel)
     setStyle(self.pStyleWeekNo, weekCel)
예제 #32
0
 def testPassThruWkst(self):
     newWkst = (calendar.firstweekday() + 2) % 7
     self.failUnlessParseMatches(
         "FREQ=WEEKLY;INTERVAL=2;BYDAY=SU,FR;WKST=%s" % (
                                         rrule.weekday(newWkst)),
         True,
         {'freq':rrule.WEEKLY, 'interval':2,
          'byweekday':(rrule.SU, rrule.FR)},
         {'wkst': newWkst} # Test passthru of wkst
     )
 def testPassThruByMinute(self):
     newWkst = (calendar.firstweekday() + 2) % 7
     self.failUnlessParseMatches(
         "FREQ=HOURLY;BYMINUTE=15,45",
         False,
         {
             'freq': rrule.HOURLY,
             'interval': 1
         },
         {'byminute': (15, 45)}  # Test passthru of wkst
     )
예제 #34
0
파일: settingGui.py 프로젝트: jomsom/empMgm
 def setWeeklyDay(self, fDay):
     if not self.weekDayOrder:
         calendar.setfirstweekday(fDay) #6 is sunday, can do like,calendar.setfirstweekday(calendar.SUNDAY)
         calObj = calendar.Calendar(calendar.firstweekday()) #cal object with firstDay as first day of week
     
         iterWeek = calObj.iterweekdays()
         #self.weekDayOrder = []
         for dayNum in iterWeek: #sets days of week according to first day of week setting
             self.weekDayOrder.append(calendar.day_abbr[dayNum])
             
         self.settingDB['weekDayOrder'] = self.weekDayOrder
         print('hello')
     print(self.weekDayOrder)
 def testPassThruWkst(self):
     newWkst = (calendar.firstweekday() + 2) % 7
     self.failUnlessParseMatches(
         "FREQ=WEEKLY;INTERVAL=2;BYDAY=SU,FR;WKST=%s" %
         (rrule.weekday(newWkst)),
         True,
         {
             'freq': rrule.WEEKLY,
             'interval': 2,
             'byweekday': (rrule.SU, rrule.FR)
         },
         {'wkst': newWkst}  # Test passthru of wkst
     )
예제 #36
0
 def _renderTemplate(self, node, year, month, ifo, links, dayrenderer):
     fd = calendar.firstweekday()
     calendar.setfirstweekday(self._firstWeekday)
     weeks = calendar.monthcalendar(year,
                                    month)  # a list of seven-item lists
     calendar.setfirstweekday(fd)
     if len(weeks) == 5:
         weeks.append([0, 0, 0, 0, 0, 0, 0])
     node.caption.content = "%s %s %s" % (ifo, self._months[month - 1], year
                                          )  # set table caption
     node.week.repeat(self._renderWeek, weeks, links,
                      self._WeekendTrackerGen(self._isSundayFirst), year,
                      month, dayrenderer)  # render weekly rows
 def testPassThruBySecond(self):
     newWkst = (calendar.firstweekday() + 2) % 7
     self.failUnlessParseMatches(
         "FREQ=HOURLY;BYMINUTE=15,45;BYSECOND=11,21,31,41",
         False,
         {
             'freq': rrule.HOURLY,
             'interval': 1
         },
         {
             'byminute': (15, 45),
             'bysecond': (11, 21, 31, 41)
         }  # Test passthru of wkst
     )
예제 #38
0
    def create_weekday_lists(self,
                             meal_plan_id,
                             meal_labels,
                             meals_in_day=None):
        if meals_in_day is None:
            meals_in_day = [
                MealType.BREAKFAST, MealType.ENTREE, MealType.VEGGIES,
                MealType.FRUIT, MealType.SIDES, MealType.ENTREE,
                MealType.SALAD, MealType.FRUIT
            ]
        for i, day in tqdm(enumerate(
                range(calendar.firstweekday(),
                      calendar.firstweekday() + len(weekday_names))),
                           file=tqdm_log,
                           unit='day',
                           total=7):
            response = self.pyllo.create_list(meal_plan_id,
                                              weekday_names[day % 7], i + 1)
            logging.debug('Create Weekday List response: %s', response.text)
            day_id = json.loads(response.text)['id']

            for meal_in_day in meals_in_day:
                self.pyllo.create_card(day_id, meal_in_day.value,
                                       meal_labels[meal_in_day])
예제 #39
0
def filter_created(queryset, name, value):
    no = localtime(now())
    middle_no = no.replace(hour=0, minute=0, second=0)
    if value == 'D':
        return queryset.filter(created__gte=middle_no, created__lte=no)
    elif value == 'W':
        monday_of_this_week = middle_no - timedelta(days=(middle_no.isocalendar()[2] - 1))
        monday_of_next_week = monday_of_this_week + timedelta(days=7)
        return queryset.filter(created__gte=monday_of_this_week, created__lt=monday_of_next_week)
    elif value == 'M':
        first_day = calendar.firstweekday()
        fist_weekday, number_of_days = calendar.monthrange(middle_no.year, middle_no.month)
        first_day_of_this_month = middle_no.replace(day=1)
        first_day_of_next_month = first_day_of_this_month + timedelta(days=number_of_days)
        return queryset.filter(created__gte=first_day_of_this_month, created__lt=first_day_of_next_month)
    
    return queryset
예제 #40
0
파일: CalendarTool.py 프로젝트: dtgit/dtedu
    def getDayNumbers(self):
        """ Returns a list of daynumbers with the correct start day first.

        >>> import calendar

        CMFCalendar / Python's calendar module and the translation service tool
        use different values for the first day of week. To get the right
        localized day names with the translation service tool we need a method
        to return the days in the order used by CMFCalendar.

        >>> fwday = (calendar.firstweekday()+1) % 7

        >>> ctool = CalendarTool()

        >>> ctool.getDayNumbers()[0] == fwday
        True
        """
        firstweekday = calendar.firstweekday()+1
        return [i%7 for i in range(firstweekday, firstweekday + 7)]
예제 #41
0
def testB():
    print("\tCalendar")
    print(calendar.weekheader(3))
    print(calendar.firstweekday())
    print(calendar.month(2018, 4))
    print(calendar.calendar(2010))
    print(calendar.calendar(2011))
    print("Lunes vale: ", calendar.MONDAY)
    print("Martes vale: ", calendar.TUESDAY)
    print("Miercoles vale: ", calendar.WEDNESDAY)
    print("Jueves vale: ", calendar.THURSDAY)
    print("Viernes vale: ", calendar.FRIDAY)
    print("Sabado vale: ", calendar.SATURDAY)
    print("Domingo vale: ", calendar.SUNDAY)
    dia_de_la_semana = calendar.weekday(2011, 12, 18)
    print("Dia de la semana: ", dia_de_la_semana)
    print("Dia de la semana: ", get_dia_de_semana(dia_de_la_semana))
    is_leap = calendar.isleap(2011)
    bisiesto = "Fue año bisiesto" if is_leap == True else "No fue año bisiesto"
    print(bisiesto)
예제 #42
0
def execute(macro, text):
    request = macro.request
    formatter = macro.formatter
    _ = request.getText

    # return immediately if getting links for the current page
    if request.mode_getpagelinks:
        return ''

    currentyear, currentmonth, currentday, h, m, s, wd, yd, ds = request.user.getTime(
        time.time())
    thispage = formatter.page.page_name
    # does the url have calendar params (= somebody has clicked on prev/next links in calendar) ?
    if 'calparms' in macro.request.args:
        has_calparms = 1  # yes!
        text2 = macro.request.args['calparms']
        cparmpagename, cparmyear, cparmmonth, cparmoffset, cparmoffset2, cparmheight6, cparmanniversary, cparmtemplate = \
            parseargs(request, text2, thispage, currentyear, currentmonth, 0, 0, False, False, u'')
        # Note: cparmheight6 and cparmanniversary are not used, they are just there
        # to have a consistent parameter string in calparms and macro args
    else:
        has_calparms = 0

    if text is None:  # macro call without parameters
        text = u''

    # parse and check arguments
    parmpagename, parmyear, parmmonth, parmoffset, parmoffset2, parmheight6, anniversary, parmtemplate = \
        parseargs(request, text, thispage, currentyear, currentmonth, 0, 0, False, False, u'')

    # does url have calendar params and is THIS the right calendar to modify (we can have multiple
    # calendars on the same page)?
    #if has_calparms and (cparmpagename,cparmyear,cparmmonth,cparmoffset) == (parmpagename,parmyear,parmmonth,parmoffset):

    # move all calendars when using the navigation:
    if has_calparms and cparmpagename == parmpagename:
        year, month = yearmonthplusoffset(parmyear, parmmonth,
                                          parmoffset + cparmoffset2)
        parmoffset2 = cparmoffset2
        parmtemplate = cparmtemplate
    else:
        year, month = yearmonthplusoffset(parmyear, parmmonth, parmoffset)

    if request.isSpiderAgent and abs(currentyear - year) > 1:
        return ''  # this is a bot and it didn't follow the rules (see below)
    if currentyear == year:
        attrs = {}
    else:
        attrs = {
            'rel': 'nofollow'
        }  # otherwise even well-behaved bots will index forever

    # get the calendar
    monthcal = calendar.monthcalendar(year, month)

    # european / US differences
    months = ('January', 'February', 'March', 'April', 'May', 'June', 'July',
              'August', 'September', 'October', 'November', 'December')
    # Set things up for Monday or Sunday as the first day of the week
    if calendar.firstweekday() == calendar.MONDAY:
        wkend = (5, 6)
        wkdays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
    if calendar.firstweekday() == calendar.SUNDAY:
        wkend = (0, 6)
        wkdays = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')

    colorstep = 85
    p = Page(request, thispage)
    qpagenames = '*'.join(
        [wikiutil.quoteWikinameURL(pn) for pn in parmpagename])
    qtemplate = wikiutil.quoteWikinameURL(parmtemplate)
    querystr = "calparms=%%s,%d,%d,%d,%%d,,,%%s" % (parmyear, parmmonth,
                                                    parmoffset)
    prevlink = p.url(request,
                     querystr % (qpagenames, parmoffset2 - 1, qtemplate))
    nextlink = p.url(request,
                     querystr % (qpagenames, parmoffset2 + 1, qtemplate))
    prevylink = p.url(request,
                      querystr % (qpagenames, parmoffset2 - 12, qtemplate))
    nextylink = p.url(request,
                      querystr % (qpagenames, parmoffset2 + 12, qtemplate))

    prevmonth = formatter.url(1, prevlink, 'cal-link', **
                              attrs) + '&lt;' + formatter.url(0)
    nextmonth = formatter.url(1, nextlink, 'cal-link', **
                              attrs) + '&gt;' + formatter.url(0)
    prevyear = formatter.url(1, prevylink, 'cal-link', **
                             attrs) + '&lt;&lt;' + formatter.url(0)
    nextyear = formatter.url(1, nextylink, 'cal-link', **
                             attrs) + '&gt;&gt;' + formatter.url(0)

    if parmpagename != [thispage]:
        pagelinks = ''
        r, g, b = (255, 0, 0)
        l = len(parmpagename[0])
        steps = len(parmpagename)
        maxsteps = (255 / colorstep)
        if steps > maxsteps:
            steps = maxsteps
        chstep = int(l / steps)
        st = 0
        while st < l:
            ch = parmpagename[0][st:st + chstep]
            r, g, b = cliprgb(r, g, b)
            link = Page(request, parmpagename[0]).link_to(
                request,
                ch,
                rel='nofollow',
                style=
                'background-color:#%02x%02x%02x;color:#000000;text-decoration:none'
                % (r, g, b))
            pagelinks = pagelinks + link
            r, g, b = (r, g + colorstep, b)
            st = st + chstep
        r, g, b = (255 - colorstep, 255, 255 - colorstep)
        for page in parmpagename[1:]:
            link = Page(request, page).link_to(
                request,
                page,
                rel='nofollow',
                style=
                'background-color:#%02x%02x%02x;color:#000000;text-decoration:none'
                % (r, g, b))
            pagelinks = pagelinks + '*' + link
        showpagename = '   %s<BR>\n' % pagelinks
    else:
        showpagename = ''
    if calendar.firstweekday() == calendar.SUNDAY:
        resth1 = '  <th colspan="7" class="cal-header">\n' \
                 '%s' \
                 '   %s&nbsp;%s&nbsp;<b>&nbsp;%s&nbsp;%s</b>&nbsp;%s\n&nbsp;%s\n' \
                 '  </th>\n' % (showpagename, prevyear, prevmonth, months[month-1], str(year), nextmonth, nextyear)
    if calendar.firstweekday() == calendar.MONDAY:
        resth1 = '  <th colspan="7" class="cal-header">\n' \
                 '%s' \
                 '   %s&nbsp;%s&nbsp;<b>&nbsp;%s&nbsp;/&nbsp;%s</b>&nbsp;%s\n&nbsp;%s\n' \
                 '  </th>\n' % (showpagename, prevyear, prevmonth, str(year), month, nextmonth, nextyear)
    restr1 = ' <tr>\n%s </tr>\n' % resth1

    r7 = range(7)
    restd2 = []
    for wkday in r7:
        wday = _(wkdays[wkday])
        if wkday in wkend:
            cssday = "cal-weekend"
        else:
            cssday = "cal-workday"
        restd2.append('  <td class="%s">%s</td>\n' % (cssday, wday))
    restr2 = ' <tr>\n%s </tr>\n' % "".join(restd2)

    if parmheight6:
        while len(monthcal) < 6:
            monthcal = monthcal + [[0, 0, 0, 0, 0, 0, 0]]

    maketip_js = []
    restrn = []
    for week in monthcal:
        restdn = []
        for wkday in r7:
            day = week[wkday]
            if not day:
                restdn.append('  <td class="cal-invalidday">&nbsp;</td>\n')
            else:
                page = parmpagename[0]
                if anniversary:
                    link = "%s/%02d-%02d" % (page, month, day)
                else:
                    link = "%s/%4d-%02d-%02d" % (page, year, month, day)
                daypage = Page(request, link)
                if daypage.exists() and request.user.may.read(link):
                    csslink = "cal-usedday"
                    query = {}
                    r, g, b, u = (255, 0, 0, 1)
                    daycontent = daypage.get_raw_body()
                    header1_re = re.compile(r'^\s*=\s(.*)\s=$',
                                            re.MULTILINE)  # re.UNICODE
                    titletext = []
                    for match in header1_re.finditer(daycontent):
                        if match:
                            title = match.group(1)
                            title = wikiutil.escape(title).replace("'", "\\'")
                            titletext.append(title)
                    tipname_unescaped = link.replace("'", "\\'")
                    link = wikiutil.escape(link).replace("'", "\\'")
                    tipname = link
                    tiptitle = link
                    tiptext = '<br>'.join(titletext)
                    maketip_js.append("maketip('%s','%s','%s');" %
                                      (tipname, tiptitle, tiptext))
                    attrs = {
                        'onMouseOver': "tip('%s')" % tipname_unescaped,
                        'onMouseOut': "untip()"
                    }
                else:
                    csslink = "cal-emptyday"
                    if parmtemplate:
                        query = {'action': 'edit', 'template': parmtemplate}
                    else:
                        query = {}
                    r, g, b, u = (255, 255, 255, 0)
                    if wkday in wkend:
                        csslink = "cal-weekend"
                    attrs = {'rel': 'nofollow'}
                for otherpage in parmpagename[1:]:
                    otherlink = "%s/%4d-%02d-%02d" % (otherpage, year, month,
                                                      day)
                    otherdaypage = Page(request, otherlink)
                    if otherdaypage.exists():
                        csslink = "cal-usedday"
                        if u == 0:
                            r, g, b = (r - colorstep, g, b - colorstep)
                        else:
                            r, g, b = (r, g + colorstep, b)
                r, g, b = cliprgb(r, g, b)
                style = 'background-color:#%02x%02x%02x' % (r, g, b)
                fmtlink = formatter.url(1, daypage.url(request,
                                                       query), csslink, **
                                        attrs) + str(day) + formatter.url(0)
                if day == currentday and month == currentmonth and year == currentyear:
                    cssday = "cal-today"
                    fmtlink = "<b>%s</b>" % fmtlink  # for browser with CSS probs
                else:
                    cssday = "cal-nottoday"
                restdn.append('  <td style="%s" class="%s">%s</td>\n' %
                              (style, cssday, fmtlink))
        restrn.append(' <tr>\n%s </tr>\n' % "".join(restdn))

    restable = '<table border="2" cellspacing="2" cellpadding="2">\n<col width="14%%" span="7">%s%s%s</table>\n'
    restable = restable % (restr1, restr2, "".join(restrn))

    if maketip_js:
        tip_js = '''<script language="JavaScript" type="text/javascript">
<!--
%s
// -->
</script>
''' % '\n'.join(maketip_js)
    else:
        tip_js = ''

    result = """\
<script type="text/javascript" src="%s/common/js/infobox.js"></script>
<div id="%s" style="position:absolute; visibility:hidden; z-index:20; top:-999em; left:0px;"></div>
%s%s
""" % (request.cfg.url_prefix_static, formatter.make_id_unique('infodiv'),
       tip_js, restable)
    return formatter.rawHTML(result)
예제 #43
0
thismonth_num = date_today.month  
if thismonth_num == 12:
    nextmonth_num = 1
    nextmonth_calendar_year = nextyear
else:
    nextmonth_num = date_today.month + 1
    nextmonth_calendar_year = thisyear
thismonth_calendar = calendar.monthcalendar(thisyear, thismonth_num)
nextmonth_calendar = calendar.monthcalendar(thisyear, nextmonth_num)
thismonth = calendar.month_name[thismonth_num]
nextmonth = calendar.month_name[nextmonth_num]
monthrange_thismonth = calendar.monthrange(thisyear, thismonth_num)
monthrange_nextmonth = calendar.monthrange(thisyear, nextmonth_num)
days_in_thismonth = monthrange_thismonth[1]
days_in_nextmonth = monthrange_nextmonth[1]
firstweekday_num = calendar.firstweekday()
firstweekday = calendar.day_name[firstweekday_num]
weekheader_chars = 3
weekheaders = calendar.weekheader(weekheader_chars) #(n) specifies the width in characgters for one weekday 
today_dayofmonth_num = date_today.day
today_dayofweek_num = date_today.weekday()
today_dayofweek_name =  calendar.day_name[today_dayofweek_num] #day name is san array 
today_dayofweek_abbr = calendar.day_abbr[today_dayofweek_num] 

#Define get_item function
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

  
def facebook(request):
예제 #44
0
def monthweeks(year=None, month=None, daydate=None, firstweekday=None):
    """Return an iterable of week tuples where each element in the week
    tuple is an instance of *datetime.date*.  If *daydate* is ommitted
    then the date chosen is based on the *year* and *month*.
    
    The following are equivalent.
    
      >>> from datetime import date
      >>> import calendar
      
    Using a daydate means the actual day gets ignored.

      >>> list(monthweeks(2006, 2)) == \\
      ...     list(monthweeks(daydate=date(2006, 2, 13)))
      True
      
    Now lets check out some week day values.
    
      >>> weeks = list(monthweeks(2006, 2, firstweekday=calendar.SUNDAY))
      >>> weeks[0][0]
      datetime.date(2006, 1, 29)
      
    The last day of the first week will be February 4, 2006.

      >>> weeks[0][-1]
      datetime.date(2006, 2, 4)
      
    The first day of the last week will be February 26, 2006.

      >>> weeks[-1][0]
      datetime.date(2006, 2, 26)

    The last day of the last week will be March 4, 2006.
    
      >>> weeks[-1][-1]
      datetime.date(2006, 3, 4)

    For a month where the last day of the month is the last day of the
    week.
    
      >>> weeks = list(monthweeks(2006, 9, firstweekday=calendar.SUNDAY))
      >>> weeks[-1][-1]
      datetime.date(2006, 9, 30)

    At one point when you used the last month while retrieving the weeks
    it would send the mechanism into an infinite loop until it raised 
    OverflowError.  Lets make sure that doesn't happen again.

      >>> weeks = list(monthweeks(daydate=date(2006, 12, 1), 
      ...                         firstweekday=calendar.SUNDAY))
      >>> weeks[0][0]
      datetime.date(2006, 11, 26)
      >>> weeks[-1][-1]
      datetime.date(2007, 1, 6)
      
    And now for testing another year.
    
      >>> weeks = list(monthweeks(2007, 1, firstweekday=calendar.SUNDAY))
      >>> weeks[0][0]
      datetime.date(2006, 12, 31)

    One last test, lets cycle through the months over a multi-year period
    and make sure we don't get any OverflowError's.
    
      >>> count = 0
      >>> for year in range(2002, 2006):
      ...     for month in range(1, 13):
      ...         x = monthweeks(year, month, firstweekday=calendar.SUNDAY)
      ...         x = monthweeks(year, month, firstweekday=calendar.MONDAY)
      ...         count += 1
      >>> count
      48

    """
    
    if firstweekday == None:
        firstweekday = calendar.firstweekday()

    if firstweekday == 0:
        lastweekday = 6
    else:
        lastweekday = firstweekday - 1
    
    if daydate is None:
        today = datetime.date.today()
        y = year or today.year
        m = month or today.month
        firstdate = datetime.date(y, m, 1)
    else:
        firstdate = datetime.date(daydate.year,
                                  daydate.month,
                                  1)

    firstcalday = firstdate
    while calendar.weekday(firstcalday.year, 
                           firstcalday.month, 
                           firstcalday.day) != firstweekday:
        firstcalday -= ONEDAY
    
    weeks = []
    day = firstcalday
    nextday = day + ONEDAY
    weekday = calendar.weekday(day.year, day.month, day.day)

    # see if block at bottom of while block for break conditions
    max = 100
    count = 0
    while count < max:
        if weekday == firstweekday:
            week = []
            weeks.append(week)
        week.append(day)
        
        if weekday == lastweekday:
            if nextday.month > firstdate.month or \
                  nextday.year > firstdate.year:
                break

        day += ONEDAY
        nextday = day + ONEDAY
        weekday = calendar.weekday(day.year, day.month, day.day)

        count += 1

    if count == max:
        raise OverflowError('Counted %i days for this interval which is '
                            'not possible, something went wrong' % max)

    return (tuple(x) for x in weeks)
예제 #45
0
def month(request, year=None, month=None, change=None):
    """
    Display the days in the specified month.
    """

    # default to this month
    today, now = get_today_now()
    if not year:
        year, month = today.year, today.month
    else:
        year, month = int(year), int(month)
    date = timezone.datetime(year=year, month=month, day=15).date()

    # handle month change, with year rollover
    if change:
        monthDelta = datetime.timedelta(days=31)
        if change == 'prev': 
            monthDelta = datetime.timedelta(days=-31)
        date = date + monthDelta

    # intial values
    cal = calendar.Calendar(calendar.firstweekday())
    month_days = cal.itermonthdays(date.year, date.month)
    weeks = [[]]
    week_no = 0

    # process all the days in the month
    for day in month_days:
        entry_list = statistics = current = None
        nav_slug = None
        if day:
            dayDate = datetime.date(year=date.year, month=date.month, day=day)
            entries = (
                Entry.objects.filter(date=dayDate) if request.user.is_staff
                else Entry.objects.filter(
                    date=dayDate, 
                    customer=request.user,
                    cancelled=False,
                )
            )
            if request.user.is_staff:
                statistics = get_statistics(entries)
            else:
                entry_list = list(entries)

            nav_slug = dayDate.strftime(DATE_SLUG_FORMAT)
            current = (dayDate == today)
        weeks[week_no].append((day, nav_slug, entry_list, statistics, current))
        if len(weeks[week_no]) == 7:
            weeks.append([])
            week_no += 1

    return render_to_response(
        'diary/month.html',
        {
            'date': date,
            'weeks': weeks,
            'month_name': MONTH_NAMES[date.month-1],
            'day_names': DAY_NAMES,
            'reminders': reminders(request),
        }, 
        context_instance=RequestContext(request),
    )
예제 #46
0
파일: libs.py 프로젝트: changyuan/learn
# print(p.cmdline())
# print(p.ppid())
# print(p.parent())
# print(p.children())
# print(p.username())
# print(p.create_time())
# print(p.terminal())
# print(p.cpu_times())
# print(p.memory_info())
# print(p.open_files())
# print(p.connections())
# print(p.num_threads())
# print(p.threads())
# print(p.environ())
# print(p.terminate())


import calendar
print(calendar.isleap(2016))
print(calendar.calendar(2018))
print(calendar.month(2018,2))
print(calendar.firstweekday())
print(calendar.leapdays(2000,2018))
# calendar.prcal(2018)
# calendar.prmonth(2018,2,2,1)
print(calendar.weekday(2018, 2, 7))
print(calendar.monthcalendar(2018,2))



예제 #47
0
    def __init__(self, freq, dtstart=None,
                 interval=1, wkst=None, count=None, until=None, bysetpos=None,
                 bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
                 byweekno=None, byweekday=None,
                 byhour=None, byminute=None, bysecond=None,
                 cache=False):
        super(rrule, self).__init__(cache)
        global easter
        if not dtstart:
            dtstart = datetime.datetime.now().replace(microsecond=0)
        elif not isinstance(dtstart, datetime.datetime):
            dtstart = datetime.datetime.fromordinal(dtstart.toordinal())
        else:
            dtstart = dtstart.replace(microsecond=0)
        self._dtstart = dtstart
        self._tzinfo = dtstart.tzinfo
        self._freq = freq
        self._interval = interval
        self._count = count
        if until and not isinstance(until, datetime.datetime):
            until = datetime.datetime.fromordinal(until.toordinal())
        self._until = until
        if wkst is None:
            self._wkst = calendar.firstweekday()
        elif isinstance(wkst, integer_types):
            self._wkst = wkst
        else:
            self._wkst = wkst.weekday
        if bysetpos is None:
            self._bysetpos = None
        elif isinstance(bysetpos, integer_types):
            if bysetpos == 0 or not (-366 <= bysetpos <= 366):
                raise ValueError("bysetpos must be between 1 and 366, "
                                 "or between -366 and -1")
            self._bysetpos = (bysetpos,)
        else:
            self._bysetpos = tuple(bysetpos)
            for pos in self._bysetpos:
                if pos == 0 or not (-366 <= pos <= 366):
                    raise ValueError("bysetpos must be between 1 and 366, "
                                     "or between -366 and -1")
        if not (byweekno or byyearday or bymonthday or
                byweekday is not None or byeaster is not None):
            if freq == YEARLY:
                if not bymonth:
                    bymonth = dtstart.month
                bymonthday = dtstart.day
            elif freq == MONTHLY:
                bymonthday = dtstart.day
            elif freq == WEEKLY:
                byweekday = dtstart.weekday()
        # bymonth
        if not bymonth:
            self._bymonth = None
        elif isinstance(bymonth, integer_types):
            self._bymonth = (bymonth,)
        else:
            self._bymonth = tuple(bymonth)
        # byyearday
        if not byyearday:
            self._byyearday = None
        elif isinstance(byyearday, integer_types):
            self._byyearday = (byyearday,)
        else:
            self._byyearday = tuple(byyearday)
        # byeaster
        if byeaster is not None:
            if not easter:
                from dateutil import easter
            if isinstance(byeaster, integer_types):
                self._byeaster = (byeaster,)
            else:
                self._byeaster = tuple(byeaster)
        else:
            self._byeaster = None
        # bymonthay
        if not bymonthday:
            self._bymonthday = ()
            self._bynmonthday = ()
        elif isinstance(bymonthday, integer_types):
            if bymonthday < 0:
                self._bynmonthday = (bymonthday,)
                self._bymonthday = ()
            else:
                self._bymonthday = (bymonthday,)
                self._bynmonthday = ()
        else:
            self._bymonthday = tuple([x for x in bymonthday if x > 0])
            self._bynmonthday = tuple([x for x in bymonthday if x < 0])
        # byweekno
        if byweekno is None:
            self._byweekno = None
        elif isinstance(byweekno, integer_types):
            self._byweekno = (byweekno,)
        else:
            self._byweekno = tuple(byweekno)
        # byweekday / bynweekday
        if byweekday is None:
            self._byweekday = None
            self._bynweekday = None
        elif isinstance(byweekday, integer_types):
            self._byweekday = (byweekday,)
            self._bynweekday = None
        elif hasattr(byweekday, "n"):
            if not byweekday.n or freq > MONTHLY:
                self._byweekday = (byweekday.weekday,)
                self._bynweekday = None
            else:
                self._bynweekday = ((byweekday.weekday, byweekday.n),)
                self._byweekday = None
        else:
            self._byweekday = []
            self._bynweekday = []
            for wday in byweekday:
                if isinstance(wday, integer_types):
                    self._byweekday.append(wday)
                elif not wday.n or freq > MONTHLY:
                    self._byweekday.append(wday.weekday)
                else:
                    self._bynweekday.append((wday.weekday, wday.n))
            self._byweekday = tuple(self._byweekday)
            self._bynweekday = tuple(self._bynweekday)
            if not self._byweekday:
                self._byweekday = None
            elif not self._bynweekday:
                self._bynweekday = None
        # byhour
        if byhour is None:
            if freq < HOURLY:
                self._byhour = (dtstart.hour,)
            else:
                self._byhour = None
        elif isinstance(byhour, integer_types):
            self._byhour = (byhour,)
        else:
            self._byhour = tuple(byhour)
        # byminute
        if byminute is None:
            if freq < MINUTELY:
                self._byminute = (dtstart.minute,)
            else:
                self._byminute = None
        elif isinstance(byminute, integer_types):
            self._byminute = (byminute,)
        else:
            self._byminute = tuple(byminute)
        # bysecond
        if bysecond is None:
            if freq < SECONDLY:
                self._bysecond = (dtstart.second,)
            else:
                self._bysecond = None
        elif isinstance(bysecond, integer_types):
            self._bysecond = (bysecond,)
        else:
            self._bysecond = tuple(bysecond)

        if self._freq >= HOURLY:
            self._timeset = None
        else:
            self._timeset = []
            for hour in self._byhour:
                for minute in self._byminute:
                    for second in self._bysecond:
                        self._timeset.append(
                                datetime.time(hour, minute, second,
                                                    tzinfo=self._tzinfo))
            self._timeset.sort()
            self._timeset = tuple(self._timeset)
예제 #48
0
import calendar
import datetime

while
  if calendar.firstweekday( ) == 6:
      i ++

예제 #49
0
#-*- coding: utf-8 -*-
# enaltacleaner

import glob, os
import time
import calendar

from threading import Timer
from datetime import datetime
from zipfile import ZipFile
from datetime import date

# shelledure task
agendamento = calendar.firstweekday()
hoje = date.today()

def limpeza():
        # zip files
        meuzip = ZipFile('arquivo-' + str(hoje) + '.zip', 'a')
        meuzip.write('/inetpub/wwwroot/enalta.integracao.server/bkp/enalta.integracao.server/log/Backup/')
        meuzip.close()

        # sendmail with attachment
        
        # remove zipfile
        filelist = glob.glob("*.zip")
        for f in filelist:
                os.remove(f)

        # clear folder
        for root, dirs, files in os.walk('/inetpub/wwwroot/enalta.integracao.server/bkp/enalta.integracao.server/log/Backup/*/'):
예제 #50
0
 def setUp(self):
     self.oldfirstweekday = calendar.firstweekday()
     calendar.setfirstweekday(self.firstweekday)
예제 #51
0
# Create your views here.

from .models import Entry, Customer
from .forms import EntryForm
from .admin import CustomerCreationForm, CustomerChangeForm
from . import settings


# set the first day of the week (default 0=monday)
# (uses settings variable DIARY_FIRST_DAY_OF_WEEK)
calendar.setfirstweekday(settings.DIARY_FIRST_DAY_OF_WEEK)


MONTH_NAMES = calendar.month_name[1:]
DAY_NAMES = (
    calendar.day_name[calendar.firstweekday():] + 
    calendar.day_name[:calendar.firstweekday()]
)


# format definitions for the date and time slugs
DATE_SLUG_FORMAT = '%Y-%m-%d'
TIME_SLUG_FORMAT = '%H-%M'
DATETIME_SLUG_FORMAT = '%Y-%m-%d_%H-%M'

# choose 12-hour or 24-hour time display format from meridian settings
TIME_FORMAT = '%I:%M' if settings.DIARY_SHOW_MERIDIAN else '%H:%M'

# entry title date format
ENTRY_DATE_FORMAT = '%a %d %b %Y'
예제 #52
0
파일: rrule.py 프로젝트: dwd/Polymer
    def __init__(self, freq, dtstart=None,
                 interval=1, wkst=None, count=None, until=None, bysetpos=None,
                 bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
                 byweekno=None, byweekday=None,
                 byhour=None, byminute=None, bysecond=None,
                 cache=False):
        rrulebase.__init__(self, cache)
        global easter
        if not dtstart:
            dtstart = datetime.datetime.now().replace(microsecond=0)
        elif not isinstance(dtstart, datetime.datetime):
            dtstart = datetime.datetime.fromordinal(dtstart.toordinal())
        else:
            dtstart = dtstart.replace(microsecond=0)
        self._dtstart = dtstart
        self._tzinfo = dtstart.tzinfo
        self._freq = freq
        self._interval = interval
        self._count = count
        if until and not isinstance(until, datetime.datetime):
            until = datetime.datetime.fromordinal(until.toordinal())
        self._until = until
        if wkst is None:
            self._wkst = calendar.firstweekday()
        elif type(wkst) is int:
            self._wkst = wkst
        else:
            self._wkst = wkst.weekday
        if bysetpos is None:
            self._bysetpos = None
        elif type(bysetpos) is int:
            self._bysetpos = (bysetpos,)
        else:
            self._bysetpos = tuple(bysetpos)
        if not (byweekno or byyearday or bymonthday or
                byweekday is not None or byeaster is not None):
            if freq == FREQ_YEARLY:
                if not bymonth:
                    bymonth = dtstart.month
                bymonthday = dtstart.day
            elif freq == FREQ_MONTHLY:
                bymonthday = dtstart.day
            elif freq == FREQ_WEEKLY:
                byweekday = dtstart.weekday()
        # bymonth
        if not bymonth:
            self._bymonth = None
        elif type(bymonth) is int:
            self._bymonth = (bymonth,)
        else:
            self._bymonth = tuple(bymonth)
        # byyearday
        if not byyearday:
            self._byyearday = None
        elif type(byyearday) is int:
            self._byyearday = (byyearday,)
        else:
            self._byyearday = tuple(byyearday)
        # byeaster
        if byeaster is not None:
            if not easter:
                from dateutil import easter
            if type(byeaster) is int:
                self._byeaster = (byeaster,)
            else:
                self._byeaster = tuple(byeaster)
        else:
            self._byeaster = None
        # bymonthay
        if not bymonthday:
            self._bymonthday = ()
            self._bynmonthday = ()
        elif type(bymonthday) is int:
            if bymonthday < 0:
                self._bynmonthday = (bymonthday,)
                self._bymonthday = ()
            else:
                self._bymonthday = (bymonthday,)
                self._bynmonthday = ()
        else:
            self._bymonthday = tuple([x for x in bymonthday if x > 0])
            self._bynmonthday = tuple([x for x in bymonthday if x < 0])
        # byweekno
        if byweekno is None:
            self._byweekno = None
        elif type(byweekno) is int:
            self._byweekno = (byweekno,)
        else:
            self._byweekno = tuple(byweekno)
        # byweekday / bynweekday
        if byweekday is None:
            self._byweekday = None
            self._bynweekday = None
        elif type(byweekday) is int:
            self._byweekday = (byweekday,)
            self._bynweekday = None
        elif hasattr(byweekday, "n"):
            if byweekday.n == 0 or freq > FREQ_MONTHLY:
                self._byweekday = (byweekday.weekday,)
                self._bynweekday = None
            else:
                self._bynweekday = ((byweekday.weekday, byweekday.n),)
                self._byweekday = None
        else:
            self._byweekday = []
            self._bynweekday = []
            for wday in byweekday:
                if type(wday) is int:
                    self._byweekday.append(wday)
                elif wday.n == 0 or freq > FREQ_MONTHLY:
                    self._byweekday.append(wday.weekday)
                else:
                    self._bynweekday.append((wday.weekday, wday.n))
            self._byweekday = tuple(self._byweekday)
            self._bynweekday = tuple(self._bynweekday)
            if not self._byweekday:
                self._byweekday = None
            elif not self._bynweekday:
                self._bynweekday = None
        # byhour
        if byhour is None:
            if freq < FREQ_HOURLY:
                self._byhour = (dtstart.hour,)
            else:
                self._byhour = None
        elif type(byhour) is int:
            self._byhour = (byhour,)
        else:
            self._byhour = tuple(byhour)
        # byminute
        if byminute is None:
            if freq < FREQ_MINUTELY:
                self._byminute = (dtstart.minute,)
            else:
                self._byminute = None
        elif type(byminute) is int:
            self._byminute = (byminute,)
        else:
            self._byminute = tuple(byminute)
        # bysecond
        if bysecond is None:
            if freq < FREQ_SECONDLY:
                self._bysecond = (dtstart.second,)
            else:
                self._bysecond = None
        elif type(bysecond) is int:
            self._bysecond = (bysecond,)
        else:
            self._bysecond = tuple(bysecond)

        if self._freq >= FREQ_HOURLY:
            self._timeset = None
        else:
            self._timeset = []
            for hour in self._byhour:
                for minute in self._byminute:
                    for second in self._bysecond:
                        self._timeset.append(
                                datetime.time(hour, minute, second,
                                                    tzinfo=self._tzinfo))
            self._timeset.sort()
            self._timeset = tuple(self._timeset)
def execute(macro, text):
    request = macro.request
    formatter = macro.formatter
    _ = request.getText

    # return immediately if getting links for the current page
    if request.mode_getpagelinks:
        return ''

    currentyear, currentmonth, currentday, h, m, s, wd, yd, ds = request.user.getTime(time.time())
    thispage = formatter.page.page_name
    # does the url have calendar params (= somebody has clicked on prev/next links in calendar) ?
    if 'calparms' in macro.request.args:
        has_calparms = 1 # yes!
        text2 = macro.request.args['calparms']
        cparmpagename, cparmyear, cparmmonth, cparmoffset, cparmoffset2, cparmheight6, cparmanniversary, cparmtemplate = \
            parseargs(request, text2, thispage, currentyear, currentmonth, 0, 0, False, False, u'')
        # Note: cparmheight6 and cparmanniversary are not used, they are just there
        # to have a consistent parameter string in calparms and macro args
    else:
        has_calparms = 0

    if text is None: # macro call without parameters
        text = u''

    # parse and check arguments
    parmpagename, parmyear, parmmonth, parmoffset, parmoffset2, parmheight6, anniversary, parmtemplate = \
        parseargs(request, text, thispage, currentyear, currentmonth, 0, 0, False, False, u'')

    # does url have calendar params and is THIS the right calendar to modify (we can have multiple
    # calendars on the same page)?
    #if has_calparms and (cparmpagename,cparmyear,cparmmonth,cparmoffset) == (parmpagename,parmyear,parmmonth,parmoffset):

    # move all calendars when using the navigation:
    if has_calparms and cparmpagename == parmpagename:
        year, month = yearmonthplusoffset(parmyear, parmmonth, parmoffset + cparmoffset2)
        parmoffset2 = cparmoffset2
        parmtemplate = cparmtemplate
    else:
        year, month = yearmonthplusoffset(parmyear, parmmonth, parmoffset)

    if request.isSpiderAgent and abs(currentyear - year) > 1:
        return '' # this is a bot and it didn't follow the rules (see below)
    if currentyear == year:
        attrs = {}
    else:
        attrs = {'rel': 'nofollow' } # otherwise even well-behaved bots will index forever

    # get the calendar
    monthcal = calendar.monthcalendar(year, month)

    # european / US differences
    months = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
    # Set things up for Monday or Sunday as the first day of the week
    if calendar.firstweekday() == calendar.MONDAY:
        wkend = (5, 6)
        wkdays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
    if calendar.firstweekday() == calendar.SUNDAY:
        wkend = (0, 6)
        wkdays = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')

    colorstep = 85
    p = Page(request, thispage)
    qpagenames = '*'.join([wikiutil.quoteWikinameURL(pn) for pn in parmpagename])
    qtemplate = wikiutil.quoteWikinameURL(parmtemplate)
    querystr = "calparms=%%s,%d,%d,%d,%%d,,,%%s" % (parmyear, parmmonth, parmoffset)
    prevlink = p.url(request, querystr % (qpagenames, parmoffset2 - 1, qtemplate))
    nextlink = p.url(request, querystr % (qpagenames, parmoffset2 + 1, qtemplate))
    prevylink = p.url(request, querystr % (qpagenames, parmoffset2 - 12, qtemplate))
    nextylink = p.url(request, querystr % (qpagenames, parmoffset2 + 12, qtemplate))

    prevmonth = formatter.url(1, prevlink, 'cal-link', **attrs) + '&lt;' + formatter.url(0)
    nextmonth = formatter.url(1, nextlink, 'cal-link', **attrs) + '&gt;' + formatter.url(0)
    prevyear = formatter.url(1, prevylink, 'cal-link', **attrs) + '&lt;&lt;' + formatter.url(0)
    nextyear = formatter.url(1, nextylink, 'cal-link', **attrs) + '&gt;&gt;' + formatter.url(0)

    if parmpagename != [thispage]:
        pagelinks = ''
        r, g, b = (255, 0, 0)
        l = len(parmpagename[0])
        steps = len(parmpagename)
        maxsteps = (255 / colorstep)
        if steps > maxsteps:
            steps = maxsteps
        chstep = int(l / steps)
        st = 0
        while st < l:
            ch = parmpagename[0][st:st+chstep]
            r, g, b = cliprgb(r, g, b)
            link = Page(request, parmpagename[0]).link_to(request, ch,
                        rel='nofollow',
                        style='background-color:#%02x%02x%02x;color:#000000;text-decoration:none' % (r, g, b))
            pagelinks = pagelinks + link
            r, g, b = (r, g+colorstep, b)
            st = st + chstep
        r, g, b = (255-colorstep, 255, 255-colorstep)
        for page in parmpagename[1:]:
            link = Page(request, page).link_to(request, page,
                        rel='nofollow',
                        style='background-color:#%02x%02x%02x;color:#000000;text-decoration:none' % (r, g, b))
            pagelinks = pagelinks + '*' + link
        showpagename = '   %s<BR>\n' % pagelinks
    else:
        showpagename = ''
    if calendar.firstweekday() == calendar.SUNDAY:
        resth1 = '  <th colspan="7" class="cal-header">\n' \
                 '%s' \
                 '   %s&nbsp;%s&nbsp;<b>&nbsp;%s&nbsp;%s</b>&nbsp;%s\n&nbsp;%s\n' \
                 '  </th>\n' % (showpagename, prevyear, prevmonth, months[month-1], str(year), nextmonth, nextyear)
    if calendar.firstweekday() == calendar.MONDAY:
        resth1 = '  <th colspan="7" class="cal-header">\n' \
                 '%s' \
                 '   %s&nbsp;%s&nbsp;<b>&nbsp;%s&nbsp;/&nbsp;%s</b>&nbsp;%s\n&nbsp;%s\n' \
                 '  </th>\n' % (showpagename, prevyear, prevmonth, str(year), month, nextmonth, nextyear)
    restr1 = ' <tr>\n%s </tr>\n' % resth1

    r7 = range(7)
    restd2 = []
    for wkday in r7:
        wday = _(wkdays[wkday])
        if wkday in wkend:
            cssday = "cal-weekend"
        else:
            cssday = "cal-workday"
        restd2.append('  <td class="%s">%s</td>\n' % (cssday, wday))
    restr2 = ' <tr>\n%s </tr>\n' % "".join(restd2)

    if parmheight6:
        while len(monthcal) < 6:
            monthcal = monthcal + [[0, 0, 0, 0, 0, 0, 0]]

    maketip_js = []
    restrn = []
    for week in monthcal:
        restdn = []
        for wkday in r7:
            day = week[wkday]
            if not day:
                restdn.append('  <td class="cal-invalidday">&nbsp;</td>\n')
            else:
                page = parmpagename[0]
                if anniversary:
                    link = "%s/%02d-%02d" % (page, month, day)
                else:
                    link = "%s/%4d-%02d-%02d" % (page, year, month, day)
                daypage = Page(request, link)
                if daypage.exists() and request.user.may.read(link):
                    csslink = "cal-usedday"
                    query = {}
                    r, g, b, u = (255, 0, 0, 1)
                    daycontent = daypage.get_raw_body()
                    header1_re = re.compile(r'^\s*=\s(.*)\s=$', re.MULTILINE) # re.UNICODE
                    titletext = []
                    for match in header1_re.finditer(daycontent):
                        if match:
                            title = match.group(1)
                            title = wikiutil.escape(title).replace("'", "\\'")
                            titletext.append(title)
                    tipname_unescaped = link.replace("'", "\\'")
                    link = wikiutil.escape(link).replace("'", "\\'")
                    tipname = link
                    tiptitle = link
                    tiptext = '<br>'.join(titletext)
                    maketip_js.append("maketip('%s','%s','%s');" % (tipname, tiptitle, tiptext))
                    attrs = {'onMouseOver': "tip('%s')" % tipname_unescaped,
                             'onMouseOut': "untip()"}
                else:
                    csslink = "cal-emptyday"
                    if parmtemplate:
                        query = {'action': 'edit', 'template': parmtemplate}
                    else:
                        query = {}
                    r, g, b, u = (255, 255, 255, 0)
                    if wkday in wkend:
                        csslink = "cal-weekend"
                    attrs = {'rel': 'nofollow'}
                for otherpage in parmpagename[1:]:
                    otherlink = "%s/%4d-%02d-%02d" % (otherpage, year, month, day)
                    otherdaypage = Page(request, otherlink)
                    if otherdaypage.exists():
                        csslink = "cal-usedday"
                        if u == 0:
                            r, g, b = (r-colorstep, g, b-colorstep)
                        else:
                            r, g, b = (r, g+colorstep, b)
                r, g, b = cliprgb(r, g, b)
                style = 'background-color:#%02x%02x%02x' % (r, g, b)
                fmtlink = formatter.url(1, daypage.url(request, query), csslink, **attrs) + str(day) + formatter.url(0)
                if day == currentday and month == currentmonth and year == currentyear:
                    cssday = "cal-today"
                    fmtlink = "<b>%s</b>" % fmtlink # for browser with CSS probs
                else:
                    cssday = "cal-nottoday"
                restdn.append('  <td style="%s" class="%s">%s</td>\n' % (style, cssday, fmtlink))
        restrn.append(' <tr>\n%s </tr>\n' % "".join(restdn))

    restable = '<table border="2" cellspacing="2" cellpadding="2">\n<col width="14%%" span="7">%s%s%s</table>\n'
    restable = restable % (restr1, restr2, "".join(restrn))

    if maketip_js:
        tip_js = '''<script language="JavaScript" type="text/javascript">
<!--
%s
// -->
</script>
''' % '\n'.join(maketip_js)
    else:
        tip_js = ''

    result = """\
<script type="text/javascript" src="%s/common/js/infobox.js"></script>
<div id="%s" style="position:absolute; visibility:hidden; z-index:20; top:-999em; left:0px;"></div>
%s%s
""" % (request.cfg.url_prefix_static, formatter.make_id_unique('infodiv'), tip_js, restable)
    return formatter.rawHTML(result)
예제 #54
0
    print("현재 날짜 및 시간 : ", now)
    print("차이 : ", set_dt - now)

    print(date(2019, 7, 1))
    print(date.today())
    print(time(15, 30, 45))
    print(datetime.datetime(2020, 2, 14, 18, 10, 50))
    print(datetime.datetime.now())

    # 달력
    print(calendar.calendar(2019))
    print(calendar.calendar(2019, m=4))
    print(calendar.month(2020, 9))
    print(calendar.monthrange(2020, 2))
    print(calendar.firstweekday())

    # 일주일의 시작을 월 -> 일 바꿈
    calendar.setfirstweekday(calendar.SUNDAY)
    print(calendar.month(2020, 9))

    # 해당 날짜의 요일을 반환
    print(calendar.weekday(2018, 10, 14))

    # 윤년
    print(calendar.isleap(2018))
    print(calendar.isleap(2020))

else:
    print("import")
예제 #55
0
 def getFirstDayOfWeek(self):
     return calendar.firstweekday() + 1