P: n/a

Is there already a pure python module that can do modulararithmetic unit
conversions, like converting a huge number of seconds into months,
weeks... or a bandwidth measure into megabits/s or gigabits/s or
megabytes/s or gigabytes/s, whatever's the most useful (ala df h)?
Thanks!  
Share this Question
P: n/a

Dan Stromberg wrote: Is there already a pure python module that can do modulararithmetic
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'  
P: n/a

Dan Stromberg wrote: Is there already a pure python module that can do modulararithmetic unit conversions, like converting a huge number of seconds into months, weeks... or a bandwidth measure into megabits/s or gigabits/s or megabytes/s or gigabytes/s, whatever's the most useful (ala df h)?
Thanks!
Take a look at: http://home.tiscali.be/be052320/Unum_tutorial.html
From the intro:
"Unum stands for 'unitnumbers'. It is a Python module that allows to define and
manipulate true quantities, i.e. numbers with units such as 60 seconds, 500
watts, 42 milesperhour, 100 kg per square meter, 14400 bits per second, 30
dollars etc. The module validates unit consistency in arithmetic expressions; it
provides also automatic conversion and output formatting."
Michael   This discussion thread is closed Replies have been disabled for this discussion.   Question stats  viewed: 3310
 replies: 2
 date asked: Jul 18 '05
