def int_as_ordinal(i):
     """Return a string representing an int as an ordinal number."""
     num = int2word(i)
     last_num = num.split()[-1:][0]
     if last_num in NUM_ORDINAL_MAP:
         d = num.split()[0:-1]
         d.append(NUM_ORDINAL_MAP[last_num])
         return " ".join(d)
         
     return ''.join([num, human_rrule._ordinal_ending(i)])
    def text(self, date_format="%B %d, %Y", time_format="%I:%M %p"):
        """Return a recurrence rule in plain English (or whatever language, once translation
        is supported. :)
        
        `date_format`
        An optional argument that specifies the format to print dates using strftime 
        formatting rules.
        
        `time_format`
        An optional argument that specifies the format to print times using strftime
        formatting rles.
        """
        
        dtstart = self._dtstart # datetime of when each occurrence starts. Defaults to now, down to the second.
        freq = self._freq # when the recurrence recurs, secondly through yearly. Required.
        interval = self._interval # how often the recurrence happens, each time through every nth time. Defaults to 1.
        wkst = self._wkst # Week start day, ie, an int representing which day of the week starts the week, usually Sunday or Monday. Defaults to calendar.firstweekday().
        until = self._until # datetime until which the recurrence continues. Only it or count is set, not both.
        count = self._count # Number of times the event happens before it stops. Only it or until is set, not both.
        tzinfo = self._tzinfo # Time zone information. Defaults to the tzinfo of dtstart.
        bymonth = self._bymonth # Which month a yearly event recurs in.
        byweekno = self._byweekno # Which week number a yearly event recurs in.
        byyearday = self._byyearday # Which day of the year a yearly event recurs in.
        byweekday = self._byweekday # Which weekday an event recurs in.
        bynweekday = self._bynweekday # 
        byeaster = self._byeaster
        bymonthday = self._bymonthday # Relative day of the month
        bynmonthday = self._bynmonthday # Negative relative day of the month
        bysetpos = self._bysetpos # Must be between -366 and -1 or 1 and 366.
        byhour = self._byhour
        byminute = self._byminute
        bysecond = self._bysecond
        # YEARLY needs to have bymonth and bymonthday set
        # MONTHLY needs to have bymonthday set 
        # WEEKLY needs to have byweekday set
        
        text_description = []
        
        if freq == YEARLY:
            pass
        elif freq == MONTHLY:
            
            # Get the interval. "Each", "Every other", "Every third", etc.
            p_interval = rrule2text.INTERVAL[interval-1][1]
            text_description.append(p_interval)

            # bynweekday is a tuple of (weekday, week_in_month) tuples
            for rule_pair in bynweekday:

                # Get the ordinal.
                for ord in rrule2text.ORDINAL:
                    if ord[0] == rule_pair[1]:
                        text_description.append(ord[1])
                        break

                #  Get the weekday name
                p_weekday = weekday(rule_pair[0])
                name = rrule2text.WEEKDAY_MAP[unicode(p_weekday)]
                text_description.append(name)
                
                text_description.append("at")
                
                text_description.append(dtstart.strftime(time_format))
                
                # tack on "and interval" for the next item in the list
                text_description.extend(["and", p_interval])

            # remove the last "and interval" because it's hanging off the end
            # TODO improve this
            text_description = text_description[:-2]
        
        elif freq == WEEKLY:
            pass
        elif freq == DAILY:
            pass
        elif freq == HOURLY:
            pass
        elif freq == MINUTELY:
            pass
        elif freq == SECONDLY:
            pass
        else:
            raise Rrule2textError, "Frequency value of %s is not valid." % freq
        
        if count:
            text_description.append("%s %s" % (int2word(count).rstrip(), "times"))
        elif until:
            text_description.extend(["until", until.strftime(date_format)])
            
        return map(unicode, text_description)
    def _refresh_dict(self):
        # Populate the human_rrule components with values based on the properties of 
        # self.__rrule
        rr = self.__rrule
        dtstart = rr._dtstart # datetime of when each occurrence starts. Defaults to now, down to the second.
        if not rr._freq in VALID_FREQUENCIES:
            raise ValueError, "Invalid frequency in rrule: %s" % rr._freq
        freq = rr._freq # when the recurrence recurs, secondly through yearly. Required.
        interval = rr._interval # how often the recurrence happens, each time through every nth time. Defaults to 1.
        wkst = rr._wkst # Integer representing week start day, ie, an int representing which day of the week starts the week, usually 0 for Sunday or 1 for Monday. Defaults to calendar.firstweekday().
        until = rr._until # datetime until which the recurrence continues. Only it or count is set, not both.
        count = rr._count # Number of times the event happens before it stops. Only it or until is set, not both.
        tzinfo = rr._tzinfo # Time zone information. Defaults to the tzinfo of dtstart.
        bymonth = rr._bymonth # Tuple. Which month a yearly event recurs in.
        byweekno = rr._byweekno # Tuple. Which week number a yearly event recurs in.
        byyearday = rr._byyearday # Tuple. Which day of the year a yearly event recurs in.
        byweekday = rr._byweekday # Tuple. Which weekday an event recurs in.
        bynweekday = rr._bynweekday # Tuple. By the nth weekday, e.g., FR(3) is the third Friday of the period. Only used if freq is < MONTHLY
        byeaster = rr._byeaster # Tuple.
        bymonthday = rr._bymonthday # Tuple. Relative day of the month
        bynmonthday = rr._bynmonthday # Tuple. Relative day of the month, if negative (counting from the end of the month)
        bysetpos = rr._bysetpos # Tuple. For sets of seconds/minutes/hours/days/weeks/months/years, specifies which position in the list to pay attention to.
        byhour = rr._byhour # Tuple. The hour of the occurrence.
        byminute = rr._byminute # Tuple. The minutes of the occurrence.
        bysecond = rr._bysecond # Tuple. The second of the occurrence.
        timeset = rr._timeset # If freq < HOURLY and all three of hour, minute, and second are set, timeset is a tuple of datetime.times representing when the occurrence occurs. None if otherwise.
        # YEARLY needs to have bymonth and bymonthday set
        # MONTHLY needs to have bymonthday set 
        # WEEKLY needs to have byweekday set
        # Or else they will be filled in from dtstart?
        
        # Get the frequency. YEARLY, MONTHLY, etc. 
        # (What I think of as frequency, namely how often this recurrence occurs, e.g.,
        # each time, every other time, every third time, etc., rrule calls interval.)
        # self["frequency"] = FREQUENCY_MAP[freq]
        
        # Initialize the period, which is derived from the frequency. 
        if freq in [HOURLY, MINUTELY, SECONDLY]:
            self["period"] = "" # Expresing periods doesn't make sense for these frequencies (e.g., 
        else:
            self["period"] = ' '.join(["of the", PERIOD_MAP[freq]])
        self["interval"] = INTERVAL_MAP[interval]       
 
                
        if freq == YEARLY:
            self["occurrence"] = self._build_occurrence()

            
        elif freq == MONTHLY:        
            self["occurrence"] = self._build_occurrence()    
            # # bynweekday is a tuple of (weekday, week_in_period) tuples
            # for rule_pair in bynweekday:
            # 
            #     # Get the ordinal. TODO handle multiple ordinals
            #     ord_text = []
            #     ord_text.append(human_rrule.int_as_ordinal(rule_pair[1]))
            # 
            #     #  Get the weekday name
            #     p_weekday = weekday(rule_pair[0])
            #     name = [WEEKDAY_MAP[unicode(p_weekday)]]
            #     ord_text.extend(name)
            #     self["occurrence"] = " ".join(ord_text)                
                                        
        elif freq == WEEKLY:
            self["occurrence"] = self._build_occurrence()
            # check wkst to see which day of week is first
            
            
        elif freq == DAILY:
            self["occurrence"] = "day"
                          
            
        elif freq == HOURLY:
            self["occurrence"] = "hour"

        elif freq == MINUTELY:
            self["occurrence"] = "minute"

        elif freq == SECONDLY:
            self["occurrence"] = "second"
            if bymonthday:                  
                s = "".join(["of the ", human_rrule.int_as_ordinal(bymonthday[0]), " day of the month"]) # TODO work with multiple bymonthdays
                self["occurrence"] = " ".join([self["occurrence"], s])


        else:
            raise human_rruleError, "Frequency value of %s is not valid." % freq
            
        self["begin_time"] = " ".join(["starting at", self._get_starttime().strftime(DEFAULT_DATETIME_FORMAT)])
        
        if count:
            self["terminal"] = "%s times" % int2word(count).rstrip()
        elif until:
            untiltime = self._get_untiltime()
            self["terminal"] = "until %s" % untiltime.strftime(DEFAULT_DATETIME_FORMAT) if untiltime else ""
            
        self["timezone"] = tzinfo and "%s" % tzinfo or None
Exemple #4
0
def fdic_bank_failures(request):
    from int2word import int2word
    crisis_start = datetime.datetime(2009,1,1)
    end_date = datetime.datetime(2009, 12, 31)
    recent_failed_banks = BankFailure.objects.filter(closing_date__gte=crisis_start).filter(closing_date__lte=end_date).order_by('-closing_date')    
    return render_to_response('bailout/fdic/bank_failures.html', { 'num_failures': int2word(recent_failed_banks.count()), 'last_failure_year': recent_failed_banks[0].closing_date.strftime('%Y'), 'last_failure_month_day': recent_failed_banks[0].closing_date.strftime('%B %d') }, context_instance=RequestContext(request))