pure python code to do modular-arithmetic unit conversions?

Dan Bishop danb_83 at yahoo.com
Fri Jan 21 22:29:07 EST 2005


Dan Stromberg wrote:
> Is there already a pure python module that can do modular-arithmetic
unit
> conversions, like converting a huge number of seconds into months,
> weeks...

Use the divmod function.


SECONDS_PER_MONTH = 2629746  # 1/4800 of 400 Gregorian years

def convert_seconds(seconds):
"Return (months, weeks, days, hours, minutes, seconds)."
months, seconds = divmod(seconds, SECONDS_PER_MONTH)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)
return months, weeks, days, hours, minutes, seconds

def to_seconds(months, weeks, days, hours, minutes, seconds):
return (((weeks * 7 + days) * 24 + hours) * 60 + minutes) * 60 + \
seconds + months * SECONDS_PER_MONTH

>> convert_seconds(10**9)
(380, 1, 1, 1, 28, 40)
>>> to_seconds(*_)
1000000000

> or a bandwidth measure into megabits/s or gigabits/s or
> megabytes/s or gigabytes/s, whatever's the most useful (ala df -h)?

def convert_bytes(bytes):
PREFIXES = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
x = bytes
for prefix in PREFIXES:
if x < 1024:
return '%.4g %sB' % (x, prefix)
x /= 1024.
# No SI prefixes left, so revert to scientific notation
return '%.3e B' % bytes
>>> convert_bytes(40e9)
'37.25 GB'
>>> convert_bytes(2048)
'2 KB'




More information about the Python-list mailing list