pure python code to do modular-arithmetic unit conversions?

D

Dan Stromberg

Is there already a pure python module that can do modular-arithmetic 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!
 
D

Dan Bishop

Dan said:
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
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'2 KB'
 
M

Michael Spencer

Dan said:
Is there already a pure python module that can do modular-arithmetic 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 'unit-numbers'. 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 miles-per-hour, 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,218
Messages
2,571,122
Members
47,724
Latest member
Farreach2565

Latest Threads

Top