Created
April 1, 2010 05:48
-
-
Save harto/351432 to your computer and use it in GitHub Desktop.
A couple of functions for formatting timedeltas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Functions for flexibly formatting Python timedelta objects. | |
The following field codes apply: | |
d - days | |
M - minutes | |
h - hours | |
s - seconds | |
m - milliseconds | |
u - microseconds | |
""" | |
import re | |
# Microsecond conversion table | |
mc = {'u': 1} | |
mc['m'] = mc['u'] * 1000 | |
mc['s'] = mc['m'] * 1000 | |
mc['M'] = mc['s'] * 60 | |
mc['h'] = mc['M'] * 60 | |
mc['d'] = mc['h'] * 24 | |
def timedelta_parts(td, *codes): | |
""" | |
Returns a dict containing value components of a timedelta. | |
The parts always add up to the total size of the timedelta. | |
""" | |
td = abs(td) | |
microseconds = (td.days * mc['d']) + (td.seconds * mc['s']) + td.microseconds | |
parts = {} | |
for unit in ['d', 'h', 'M', 's', 'm', 'u']: | |
if unit in codes: | |
parts[unit] = microseconds / mc[unit] | |
microseconds -= parts[unit] * mc[unit] | |
return parts | |
fmt_codes = re.compile(r'%(?P<args>[^a-zA-Z]*)(?P<code>[dhMsmu])') | |
def format_timedelta(td, fmt): | |
""" | |
Formats a timedelta object according to the specified format string. | |
>>> import datetime | |
>>> td = datetime.timedelta(days=2, hours=19, minutes=33, seconds=5) | |
>>> format_timedelta(td, '%02h:%02M:%02s') | |
'67:33:05' | |
>>> format_timedelta(td, '%d days, %s seconds') | |
'2 days, 70385 seconds' | |
""" | |
codes = [code for args, code in fmt_codes.findall(fmt)] | |
parts = timedelta_parts(td, *codes) | |
# Normalise special codes into named keys, i.e. %02h -> %(h)02d | |
norm_fmt = fmt_codes.sub( | |
lambda m: '%%(%(code)s)%(args)sd' % (m.groupdict()), fmt) | |
return norm_fmt % parts | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Two functions: one for decomposing a timedelta into discrete parts (hours, mins, etc.), and another for formatting timedeltas using 'standard' Python string interpolation.