0001"""
0002timeinterval
0003
0004Convert interval strings (in the form of 1w2d, etc) to
0005seconds, and back again.  Is not exactly about months or
0006years (leap years in particular).
0007
0008Accepts (y)ear, (b)month, (w)eek, (d)ay, (h)our, (m)inute, (s)econd.
0009
0010Exports only time_encode and time_decode functions.  
0011"""
0012
0013import re
0014
0015__all__ = ['time_encode', 'time_decode']
0016
0017second = 1
0018minute = second*60
0019hour = minute*60
0020day = hour*24
0021week = day*7
0022month = day*30
0023year = day*365
0024time_values = {
0025    'y': year,
0026    'b': month,
0027    'w': week,
0028    'd': day,
0029    'h': hour,
0030    'm': minute,
0031    's': second,
0032    }
0033time_ordered = time_values.items()
0034time_ordered.sort(lambda a, b: -cmp(a[1], b[1]))
0035
0036def time_encode(seconds):
0037    """Encodes a number of seconds (representing a time interval)
0038    into a form like 1h2d3s."""
0039    s = ''
0040    for char, amount in time_ordered:
0041        if seconds >= amount:
0042            i, seconds = divmod(seconds, amount)
0043            s += '%i%s' % (i, char)
0044    return s
0045
0046time_re = re.compile(r'[0-9]+[a-zA-Z]')
0047def time_decode(s):
0048    """Decodes a number in the format 1h4d3m (1 hour, 3 days, 3 minutes)
0049    into a number of seconds"""
0050    time = 0
0051    for match in time_re.finditer(s):
0052        char = match.group(0)[-1].lower()
0053        if not time_values.has_key(char):
0054            # @@: should signal error
0055            continue
0056        time += int(match.group(0)[:-1]) * time_values[char]
0057    return time
0058
0059__all__ = ['time_encode', 'time_decode']