简体   繁体   English

在Python中有效地转换时间

[英]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. 但是,在读取此数据时,看到10000000000微秒并不是很漂亮。 Something like x seconds, or x minutes, looks better. 像x秒或x分钟之类的东西看起来更好。

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. 在这些约束下,我想知道如何将相同的逻辑实现为更具可读性(也许使用等效于python的python)形式,并将其放入while循环中。

Thanks everyone. 感谢大家。

python has this facility built into itself python本身内置了此功能

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) 那就是说,如果您真的想要,可以通过在顶部(或在time_util.py文件等中)定义一些常量来使其更具可读性。

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)
...

Use the datetime module with a timedelta object. datetime模块与timedelta对象一起使用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM