Edgewall Software

Ticket #4547: datefmt.patch

File datefmt.patch, 2.0 KB (added by Dave Abrahams <dave@…>, 17 months ago)

updated patch for more resiliency

  • datefmt.py

     
    3131def pretty_timedelta(time1, time2=None, resolution=None): 
    3232    """Calculate time delta (inaccurately, only for decorative purposes ;-) for 
    3333    prettyprinting. If time1 is None, the current time is used.""" 
    34     if not time1: time1 = datetime.now(utc) 
    35     if not time2: time2 = datetime.now(utc) 
     34    time1 = _normalize(time1) 
     35    time2 = _normalize(time2) 
    3636    if time1 > time2: 
    3737        time2, time1 = time1, time2 
    3838    units = ((3600 * 24 * 365, 'year',   'years'), 
     
    5454            return '%d %s' % (r, r == 1 and unit or unit_plural) 
    5555    return '' 
    5656 
     57def _normalize(t, tzinfo = None): 
     58    if t is None: 
     59        return datetime.now(utc) 
     60    elif isinstance(t, (int,long,float)): 
     61        return datetime.fromtimestamp(t, tzinfo or localtz) 
     62    elif not isinstance(t,datetime): 
     63        raise TypeError, 'expecting datetime, int, long, float, or None; got %s' \ 
     64              % type(t) 
     65    else: 
     66        return t 
     67     
    5768def format_datetime(t=None, format='%x %X', tzinfo=None): 
    58     if not tzinfo: 
    59         tzinfo = localtz 
    60     if t is None: 
    61         t = datetime.now(utc) 
    62     if isinstance(t, (int,long)): 
    63         t = datetime.fromtimestamp(t, tzinfo) 
     69    t = _normalize(t, tzinfo).astimezone(tzinfo or localtz) 
    6470    if format.lower() == 'iso8601': 
    6571        format = '%Y-%m-%dT%H:%M:%SZ%z' 
    66     t = t.astimezone(tzinfo) 
    6772    text = t.strftime(format) 
    6873    encoding = locale.getpreferredencoding() or sys.getdefaultencoding() 
    6974    if sys.platform != 'win32': 
     
    97102 
    98103def http_date(t=None): 
    99104    """Format t as a rfc822 timestamp""" 
    100     if t is None: 
    101         t = datetime.now(utc) 
    102     t = t.astimezone(utc) 
     105    t = _normalize(t).astimezone(utc) 
    103106    weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] 
    104107    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 
    105108              'Oct', 'Nov', 'Dec']