By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,100 Members | 2,979 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,100 IT Pros & Developers. It's quick & easy.

pure python code to do modular-arithmetic unit conversions?

P: n/a

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!

Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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'

Jul 18 '05 #2

P: n/a
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... 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

Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.