Ryan
Ryan

Reputation: 354

Converting time efficiently in Python

I have a program that does some parsing and takes in time in a microsecond format. However, when reading this data, it's not very pretty to see 10000000000 microseconds. Something like x seconds, or x minutes, looks better.

So.. I built this:

def convert_micro_input(micro_time):
    t = int(micro_time)
    if t<1000: #millisecond
        return str(t) +' us'
    elif t<1000000: #second
        return str(int(t/1000))         +   ' ms'
    elif t<60000000: #is a second
        return str(int(t/1000000))      +   ' second(s)'
    elif t<3600000000:
        return str(int(t/60000000))     +   ' minute(s)'
    elif t<86400000000:
        return str(int(t/3600000000))   +   ' hour(s)'
    elif t<604800000000:
        return str(int(t/86400000000))  +   ' day(s)'
    else:
        print 'Exceeded Time Conversion Possibilities'
        return None

Now, in my eyes, this looks fine, however, my boss wasn't satisfied. He said the numbers are confusing in terms of readability if someone were to come edit this in a year and he said to make this happen in a while loop.

So, with that being said. Under these constraints, I am wondering at how to implement this same logic into a more readable (maybe using python equivalent of a macro) form and also put it in a while loop.

Thanks everyone.

Upvotes: 0

Views: 64

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 114008

python has this facility built into itself

from datetime import timedelta
for t in all_times_in_us:
    print timedelta(seconds=t/1000000.0)

taking advantage of that is the easiest(and most readable) way I think. that said if you really want to you can make it more readable by defining some constants at the top (or in a time_util.py file or something)

MICROSECOND=1
MILLISECOND=MICROSECOND*1000
SECOND=MS*1000
MINUTE=SECOND*60
HOUR=MINUTE*60
DAY=HOUR*24
WEEK=DAY*7

and use these values instead that way it is very clear what they are

eg

if t < MILLISECOND: 
    return "{time} us".format(time=t)
elif t < SECOND:
    return  "{time} ms".format(time=t//MILLISECOND)
elif t < MINUTE:
    return  "{time} seconds".format(time=t//SECOND)
...

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49310

Use the datetime module with a timedelta object.

>>> import datetime
>>> us = 96000000
>>> mytime = datetime.timedelta(microseconds=us)
>>> mytime.seconds
96

Upvotes: 0

Related Questions