Skip to content Skip to sidebar Skip to footer

Best Way To Incrementally Convert Microseconds To Their Respective Conversions In Python?

I currently have a pre-defined dictionary (ignore the letters). I want the conversions to be more robust, though. Say 33000000 microseconds gets inputted and knows to convert to 33

Solution 1:

This allows you to add conversions in a relatively natural way for strictly ascending unit stacks. It's a little more generic than big block of ifs.

units = [[1000, 'us'], 
         [1000, 'ms'], 
         [60, 's'], 
         [60, 'min'], 
         [24, 'h'], 
         [365, 'day'], 
         [None, 'year']]

defconvert(quantity):
    divisor = 1for factor, name in units:
        if factor isNoneor quantity < divisor*factor:
            return"{} {}".format(quantity/divisor, name)
        divisor *= factor

Solution 2:

This can be accomplished with a long string of if statements. Since there is no switch statement in Python, and a dictionary cannot be used for > and <, this is the best solution.

Something you might make would be:

defconvert(text):
  t = int(text)
  if t<1000: #millisecondreturnstr(t)+' us'elif t<1000000: #secondreturnstr(int(t/1000))+' ms'elif t==1000000: #is a secondreturn'1 sec'#etc.

Alternate Answer :

units = [("us", 1), ("ms", 1000), ("sec", 1000000)...]
forstring, divisor in units:
  if t==divisor:
    return"1 "+string
  elif t>divisor:
    ifround(float(t)/divisor)==1:
      return"1 "+stringelse:
      return str(int(round(float(t)/divisor)))+string+"s"

Hopefully this will be a better trade off between compactness, scalability, and readability.

Solution 3:

@Bcdan says "this is about as compact as possible". Challenge accepted.

>>> l = [("micro",1),("milli",1000),("s",1000),("m",60),("h",60)]
>>> d = {"micro":33000000}
>>> for i inrange(1,len(l)): d[l[i][0]],d[l[i-1][0]] = divmod(d[l[i-1][0]],l[i][1])
>>> d
{'m': 0, 's': 33, 'h': 0, 'milli': 0, 'micro': 0}

Don't know how useful that is to you, but I think it's neat. Not that it's readable or makes any sense...

Post a Comment for "Best Way To Incrementally Convert Microseconds To Their Respective Conversions In Python?"