Converting time efficiently in Python -
i have program parsing , takes in time in microsecond format. however, when reading data, it's not pretty see 10000000000 microseconds. x seconds, or x minutes, looks better.
so.. 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 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 eyes, looks fine, however, boss wasn't satisfied. said numbers confusing in terms of readability if come edit in year , said make happen in while loop.
so, being said. under these constraints, wondering @ how implement same logic more readable (maybe using python equivalent of macro) form , put in while loop.
thanks everyone.
python has facility built itself
from datetime import timedelta t in all_times_in_us: print timedelta(seconds=t/1000000.0)
taking advantage of easiest(and readable) way think. said if want can make more readable defining constants @ top (or in 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 way clear 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) ...
Comments
Post a Comment